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
// 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