Skip to content

Instantly share code, notes, and snippets.

@Vaibhav2002
Created November 9, 2022 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Vaibhav2002/b3ec45be0734c3e6e811b11a35b35071 to your computer and use it in GitHub Desktop.
Save Vaibhav2002/b3ec45be0734c3e6e811b11a35b35071 to your computer and use it in GitHub Desktop.
Collecting flows by using an extension function
/** Making this extension function cleans out the code a lot by removing the repetitive
flowWithLifecycle() or repeatOnLifecycle()
**/
fun <T> Flow<T>.safeCollect(
owner: LifecycleOwner,
block: (T.() -> Unit)? = null
) = owner.lifecycleScope.launch {
flowWithLifecycle(owner.lifecycle).collectLatest { block?.invoke(it) }
}
//This Extension function can easily be used like
flow.safeCollect(viewLifecycleOwner){
//Doing the work
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment