Last active
July 12, 2021 20:35
-
-
Save Aidanvii7/19af492d141b3cdc1ebc4ade0a89d482 to your computer and use it in GitHub Desktop.
Transforming Flow types to State in a lifecycle aware way
This file contains hidden or 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.compose.ui.platform.LocalLifecycleOwner | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.Lifecycle.State.CREATED | |
import androidx.lifecycle.Lifecycle.State.STARTED | |
import androidx.lifecycle.flowWithLifecycle | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.StateFlow | |
@Composable | |
fun <T> StateFlow<T>.collectAsStateWhileCreated(): State<T> = | |
collectAsStateWhile(minActiveState = CREATED) | |
@Composable | |
fun <T> StateFlow<T>.collectAsStateWhileStarted(): State<T> = | |
collectAsStateWhile(minActiveState = STARTED) | |
@Composable | |
fun <T> StateFlow<T>.collectAsStateWhile( | |
minActiveState: Lifecycle.State, | |
): State<T> = collectAsStateWhile( | |
minActiveState = minActiveState, | |
default = remember { value }, | |
) | |
@Composable | |
fun <T> Flow<T>.collectAsStateWhileCreated( | |
default: T, | |
): State<T> = collectAsStateWhile( | |
minActiveState = CREATED, | |
default = default, | |
) | |
@Composable | |
fun <T> Flow<T>.collectAsStateWhileStarted( | |
default: T, | |
): State<T> = collectAsStateWhile( | |
minActiveState = STARTED, | |
default = default, | |
) | |
@Composable | |
fun <T> Flow<T>.collectAsStateWhile( | |
minActiveState: Lifecycle.State, | |
default: T, | |
): State<T> { | |
@Suppress("NON_EXHAUSTIVE_WHEN") | |
when (minActiveState) { | |
Lifecycle.State.INITIALIZED, | |
Lifecycle.State.DESTROYED -> { | |
throw IllegalArgumentException("Only supports lifecycle states CREATED, STARTED and RESUMED") | |
} | |
} | |
val lifecycleOwner = LocalLifecycleOwner.current | |
return remember(default, lifecycleOwner) { | |
flowWithLifecycle( | |
lifecycle = lifecycleOwner.lifecycle, | |
minActiveState = minActiveState, | |
) | |
}.collectAsState(initial = default) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment