I have a third party library that periodically queries my video player (ExoPlayer) for information such as current position in the video. This third party library runs on a background thread. Problem is, the ExoPlayer instance is not allowed to be accessed by a background thread.
One of my ideas was to use coroutines to force a switch to the main thread before accessing the ExoPlayer instance. Something like this (note that this is called from multiple places, both on main and background threads):
suspend fun getCurrentPosition(): Long { if (Looper.myLooper() != Looper.getMainLooper()) { // On a background thread, switch to main thread and return current position return withContext(Dispatchers.Main) { exoPlayerInstance.currentPosition } } else { // Already on main thread, no need to switch threads return exoPlayerInstance.currentPosition } } Then I would call this with runBlocking like so:
runBlocking { videoPlayerWrapper.getCurrentPosition() } runBlocking is used because the third party library expects an instant result.
This works sometimes but other times my app is completely locking up. Any idea what might be wrong? Any alternative solutions?