Skip to content

Instantly share code, notes, and snippets.

@Pulimet
Created February 12, 2022 07:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pulimet/266fe04d2be109b16d3d106984f583f8 to your computer and use it in GitHub Desktop.
Save Pulimet/266fe04d2be109b16d3d106984f583f8 to your computer and use it in GitHub Desktop.
// 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