Skip to content

Instantly share code, notes, and snippets.

@virendersran01
Forked from Vaibhav2002/FlowWithExtension.kt
Created November 24, 2022 13:10
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 virendersran01/b0677d041438ee0095829d3b4485a732 to your computer and use it in GitHub Desktop.
Save virendersran01/b0677d041438ee0095829d3b4485a732 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