Skip to content

Instantly share code, notes, and snippets.

@k0siara
Created August 8, 2021 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0siara/35d18e67a2d67f2a1201056f5b0ee862 to your computer and use it in GitHub Desktop.
Save k0siara/35d18e67a2d67f2a1201056f5b0ee862 to your computer and use it in GitHub Desktop.
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