Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Last active October 2, 2024 08:15
Show Gist options
  • Select an option

  • Save Andrew0000/76f9ee964dc52610edff6ef9315bb481 to your computer and use it in GitHub Desktop.

Select an option

Save Andrew0000/76f9ee964dc52610edff6ef9315bb481 to your computer and use it in GitHub Desktop.
collectStarted() extension for contraction of repeatOnLifecycle(Lifecycle.State.STARTED)
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
/*
* Contraction for:
* https://developer.android.com/kotlin/flow/stateflow-and-sharedflow
*/
fun <T> LifecycleOwner.collectStarted(flow: Flow<T>, collector: (T) -> Unit) {
lifecycleScope.launch {
// repeatOnLifecycle launches the block in a new coroutine every time the
// lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED.
repeatOnLifecycle(Lifecycle.State.STARTED) {
// Trigger the flow and start listening for values.
// Note that this happens when lifecycle is STARTED and stops
// collecting when the lifecycle is STOPPED
flow.collect { uiState ->
// New value received
collector(uiState)
}
}
}
}
/*
* In case of Fragment must be called in onViewCreated() stage:
*
* viewModel.someState.collectStarted(viewLifecycleOwner) { ... }
*/
fun <T> Flow<T>.collectStarted(lifecycleOwner: LifecycleOwner, collector: (T) -> Unit) {
lifecycleOwner.collectStarted(this, collector)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment