Is there anyway to collect flows only when certain condition is met. Tried using takeWhile but it is completely stopping the collect whenever the condition is false. My use case is to have collect resume again on true condition and pause on false condition.
driver.listenForKeyPress().takeWhile {
currentMode == DeviceMode.WRITE
}.collect{
//Do Something.
}
Any help is appreciated.
Thanks in advance!
Iām guessing you want filter
instead of takeWhile
. It will listen to driver.listenForKeyPress()
the entire time but will discard any elements if the predicate evaluates to false.
If you actually want start or stop listening to driver.listenForKeyPress()
based on currentMode
changing, then you have to be able to listen to currentMode
to detect changes. Something like:
// When new value arrives, transformLatest cancels the previous lambda.
currentModeAsFlow.transformLatest {
if (it == DeviceMode.WRITE) {
emitAll(driver.listenForKeyPress())
}
}
1 Like