Skip to content

Instantly share code, notes, and snippets.

@Pulimet
Created February 12, 2022 07:36
Embed
What would you like to do?
// Short way to collect StateFlow on coroutine when Activity Started.
// Useful when you need to collect one StateFlow, but could be used for many.
fun <T> StateFlow<T>.collectIt(lifecycleOwner: LifecycleOwner, function: (T) -> Unit) {
lifecycleOwner.lifecycleScope.launch {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
collect {
function.invoke(it)
}
}
}
}
// Usage example: (this - LifecycleOwner)
mainViewModel.uiState.collectIt(this) {
logIt("It: $it")
}
//---------
// Launch function on coroutine when Activity STARTED.
// Useful when you need to collect multiple StateFlows.
fun LifecycleOwner.launchOnStarted(function: () -> Unit) {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
function.invoke()
}
}
}
// Usage example:
launchOnStarted {
lifecycleScope.launch { mainViewModel.uiState.collect { } }
lifecycleScope.launch { mainViewModel.uiState2.collect { } }
lifecycleScope.launch { mainViewModel.uiState3.collect { } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment