Collecting flows by using an extension function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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