Created
August 8, 2021 15:44
-
-
Save k0siara/35d18e67a2d67f2a1201056f5b0ee862 to your computer and use it in GitHub Desktop.
LifecycleAwareState.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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