William Reed
07/26/2021, 9:11 PMfun foo(): Flow<Foo> = flow {
while (context.isActive) {
// ... process and emit ...
delay(someMutableDelay) // wait until doing this again
}
}
someMutableDelay
is a mutable var
in the same class as fun foo()
- when it is changed I want the current running delay
to be cancelled and the next iteration of the loop to start immediately. any suggestions for how to achieve this?launch
a new coroutine for the delay
and then join on it immediately after. i can add a setter on someMutableDelay
which also cancels the current delay coroutine if it is setephemient
07/26/2021, 9:37 PMWilliam Reed
07/27/2021, 5:56 PMNick Allen
07/28/2021, 3:52 AMsomeMutableDelay
is a MutableStateFlow<Long>
, this could work:
someMutableDelay
.withIndex()
.transformLatest { (i, d) ->
if (i == 0) {
delay(d)
}
emit(Unit)
}
.first()
ephemient
07/28/2021, 9:09 AMprivate val delayStateFlow = MutableStateFlow(0L)
public var delay: Long by delayStateFlow::value
to hide the MutableStateFlow as an internal implementation detailWilliam Reed
07/28/2021, 11:03 AM