Skip to content

Instantly share code, notes, and snippets.

View Vaibhav2002's full-sized avatar
:shipit:
Developing sick Android and KMP apps

Vaibhav Jaiswal Vaibhav2002

:shipit:
Developing sick Android and KMP apps
View GitHub Profile
fun <T> Flow<T>.withLifecycle(state:Lifecycle.State):Flow<T>{
return lifecycleFlow.map{ curState->
curState.isAtleast(state) //check if the current state is at least the given state
}
.flatMapLatest{
if(it) this //if the screen is visible return the current flow
else emptyFlow() // else return an empty flow
}
}
@Vaibhav2002
Vaibhav2002 / FlowWithExtension.kt
Created November 9, 2022 14:11
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) }
}
@Vaibhav2002
Vaibhav2002 / flowWithLifeycle.kt
Created November 9, 2022 14:09
Collecting Flows using flowWithLifecycle
viewLifecycleOwner.lifecycleScope.launch {
//This extension function internally uses the repeatOnLifecycle API and makes the code cleaner
flow.flowWithLifecycle(Lifecycle.State.STARTED).collect {
// Doing the work
}
}
@Vaibhav2002
Vaibhav2002 / repeatOnLifecycle.kt
Created November 9, 2022 14:06
Collecting Flows using repeatOnLifecycle
viewLifecycleOwner.lifecycleScope.launch {
// This will start the collection when the state reaches STARTED and cancels when goes below
repeatOnLifecycle(Lifecycle.State.STARTED){
flow.collect {
// Doing the work
}
}
}
@Vaibhav2002
Vaibhav2002 / launchWhenX.kt
Last active November 9, 2022 14:05
Collecting Flows using `launchWhenX` APIs
//In Fragment
//This would start collection when the lifecycle state reaches State.Created and stops when it falls below
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
flow.collect {
}
}
//This would start collection when the lifecycle state reaches State.Started and stops when it falls below