Skip to content

Instantly share code, notes, and snippets.

@XMitja
Last active August 30, 2021 04:54
Show Gist options
  • Save XMitja/89db9b629978f279372ec808d3e0f909 to your computer and use it in GitHub Desktop.
Save XMitja/89db9b629978f279372ec808d3e0f909 to your computer and use it in GitHub Desktop.
// combines flowwithlifecycle, oneach and launchin
// warning: don't use inside coroutines!
fun <T> Flow<T>.launchOnEach(
owner: LifecycleOwner,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
action: suspend (T) -> Unit,
): Job = flowWithLifecycle(owner.lifecycle, minActiveState)
.onEach(action) // order matters here, see doc
.launchIn(owner.lifecycle.coroutineScope)
// make sure it's launched in fragment.viewlifecycleowner for fragments instead of fragment.lifecycle
fun <T> Flow<T>.launchOnEach(
fragment: Fragment,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
action: suspend (T) -> Unit,
): Job = launchOnEach(fragment.viewLifecycleOwner, minActiveState, action)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment