Is there an extension on lifecycle that provides a...
# android
e
Is there an extension on lifecycle that provides a
flow
for lifecycle state changes?
k
There’s not one that I could find, but I wrote this a while back.
Copy code
channelFlow {
    val listener = LifecycleEventObserver { _, event ->
        when (event) {
            Lifecycle.Event.ON_RESUME -> trySend(PlatformLifecycle.State.Started)
            Lifecycle.Event.ON_PAUSE -> trySend(PlatformLifecycle.State.Stopped)
            else -> Unit
        }
    }

    delegate.lifecycle.addObserver(listener)
    awaitClose { delegate.lifecycle.removeObserver(listener) }
}.stateIn(coroutineScope, SharingStarted.Eagerly, initialValue = PlatformLifecycle.State.Stopped)
I only care about start and stopped, but this can be easily adapted for more granular states.
e
I wrote something similar. Was hoping there would be something in androidx but ¯\_(ツ)_/¯
i
Feel free to star the feature request: https://issuetracker.google.com/issues/176311030
1
e
Don't you mean plus1
k
Would be nice to expose this as a stateflow (if it’s implemented) since the lifecycle represents the current state of something
but I will also +1 this issue