Issue
I am subscribing to a Kotlin SharedFlow of booleans within a repeatOnLifecycle
block in Android. I want to subscribe until I receive the first true
boolean and act on it.
As soon as the first true
boolean is received I need to unsubscribe and run the processing funtion within the lifecyce scope so it gets cancelled when the lifecycle transitions to an invalid state.
When I call cancel on the current scope and embed the processing code in a NonCancellable
context it will not be cancelled on lifecycle events.
I think I would want something like a takeWhile
inlcuding the first element that did not match the predicate.
Below are some sample flows where I want to collect all elements until the $ sign:
true $ ...
false, true $ ...
false, false, true $ ...
Sample code:
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
flowOfInterest.collectLatest {
if (it) {
stopCollection()
doOnTrue()
} else {
doOnFalse()
}
}
}
}
What is the correct/simplest way to achieve this behavior?
Thanks!
Solution
You can use the first function to continue collecting until the given predicate returns true
.
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
flowOfInterest.first {
if(it) doOnTrue() else doOnFalse()
it
}
}
}
Answered By - Arpit Shukla
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)