Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Created March 19, 2023 06:46
Show Gist options
  • Save bagus2x/f47ed38b95e4e365091137f2155bda64 to your computer and use it in GitHub Desktop.
Save bagus2x/f47ed38b95e4e365091137f2155bda64 to your computer and use it in GitHub Desktop.
Observe exoplayer state / Player.Listener in jetpack compose
class ExoPlayerState(
context: Context,
private val scope: CoroutineScope
) : ExoPlayer by ExoPlayer.Builder(context).build(), Player.Listener {
@get:JvmName("playing")
var isPlaying by mutableStateOf(false)
private set
var duration by mutableStateOf(0.seconds)
private set
var currentPosition by mutableStateOf(0.seconds)
private set
init {
addListener(this)
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
super.onIsPlayingChanged(isPlaying)
this.isPlaying = isPlaying
this.duration = getDuration().milliseconds
scope.launch {
while (true) {
[email protected] = getCurrentPosition().milliseconds
delay(200)
}
}
}
}
@Composable
fun rememberExoPlayerState(
lifecycleAware: Boolean = true
): ExoPlayerState {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val exoPlayerState = remember { ExoPlayerState(context, scope) }
val lifecycleOwner = LocalLifecycleOwner.current
if (lifecycleAware) {
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> exoPlayerState.play()
Lifecycle.Event.ON_PAUSE -> exoPlayerState.pause()
else -> {}
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
exoPlayerState.release()
}
}
}
return exoPlayerState
}