https://kotlinlang.org logo
#android
Title
# android
e

eygraber

01/17/2023, 2:53 PM
Is there an extension on lifecycle that provides a
flow
for lifecycle state changes?
k

kevin.cianfarini

01/17/2023, 8:44 PM
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

eygraber

01/17/2023, 9:56 PM
I wrote something similar. Was hoping there would be something in androidx but ¯\_(ツ)_/¯
i

Ian Lake

01/17/2023, 10:56 PM
Feel free to star the feature request: https://issuetracker.google.com/issues/176311030
1
e

eygraber

01/17/2023, 10:57 PM
Don't you mean plus1
k

kevin.cianfarini

01/17/2023, 10:59 PM
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
2 Views