Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LifecycleAwareState.kt
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.flowWithLifecycle
import kotlinx.coroutines.flow.Flow
@Composable
fun <T> Flow<T>.asLifecycleAwareState(lifecycleOwner: LifecycleOwner, initialState: T) =
lifecycleAwareState(lifecycleOwner, this, initialState)
@Composable
fun <T> lifecycleAwareState(
lifecycleOwner: LifecycleOwner,
flow: Flow<T>,
initialState: T
): State<T> {
val lifecycleAwareStateFlow = remember(flow, lifecycleOwner) {
flow.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
}
return lifecycleAwareStateFlow.collectAsState(initialState)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment