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
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 | |
} | |
} |
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 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
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 | |
} | |
} |
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
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 | |
} | |
} | |
} |
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
//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 |