https://kotlinlang.org logo
#coroutines
Title
# coroutines
w

William Reed

07/26/2021, 9:11 PM
in my code I have
Copy code
fun 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?
one idea:
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 set
e

ephemient

07/26/2021, 9:37 PM
create a channel for var updates, select on receive or timeout instead of just delay
w

William Reed

07/27/2021, 5:56 PM
thanks - hadn’t thought of that 🙂
n

Nick Allen

07/28/2021, 3:52 AM
If
someMutableDelay
is a
MutableStateFlow<Long>
, this could work:
Copy code
someMutableDelay
    .withIndex()
    .transformLatest { (i, d) ->
        if (i == 0) {
            delay(d)
        }
        emit(Unit)
    }
    .first()
e

ephemient

07/28/2021, 9:09 AM
ah, that's pretty elegant, and you could even do something like
Copy code
private val delayStateFlow = MutableStateFlow(0L)
public var delay: Long by delayStateFlow::value
to hide the MutableStateFlow as an internal implementation detail
w

William Reed

07/28/2021, 11:03 AM
good idea as well
not sure which I like better tbh
2 Views