How would I encode interruptible code vs. non-inte...
# coroutines
r
How would I encode interruptible code vs. non-interruptible code? Aka ask some Job nicely to cancel, but the job itself can say no, or await until an interruptible section has been reached.
d
Copy code
withContext(NonCancellable) {
    // this will run even if the caller is cancelled
}
r
Will a
collectLastest
wait for the cancellation to go through, or would I need to lock that manually?
d
Sorry, I don't understand the question.
r
Might run it myself, but basically
Copy code
flowOf(1,2,3).collectLatest { i -> withContext(NonCancellable) { sleep(1.seconds); println(i) } }
^ will this take 3 seconds, or 0 to finish?
d
This will take three seconds, though we have a patch in the works that should make the answer be 1 second.
r
Huh. I'd prefer 3 seconds ^^
d
Could you explain why?
collectLatest
collects the latest, and in the code you've provided,
1
and
2
are clearly not the latest and can be instantly skipped.
r
I've been using
collectLastest
as part of a system where it reacts to changes from the outside world, so basically
Copy code
.collectLastest { stateX, stateY, stateZ ->
   ... execute some code based on it
}
and cancel/restart as needed once the status changes. So you're saying I should explicitly lock here for future versions of coroutines?
d
It does seem like you're using
collectLatest
for its intended purpose, and I still don't see why you'd want the answer to the above to be three seconds. Here's why we intend to make it 1 second: • Value
1
arrives. • Wait, don't process
1
! Another value is about to arrive. • Value
2
arrives. • Wait, don't process
2
! Another value is about to arrive. • Value
3
arrives. •
sleep(1.seconds)
and
println(3)
are called. Do you actually want to still start processing
1
and
2
even if you know in advance that another, more recent value is about to arrive?
r
Ah, here it's different because the flowOf() supplies the value immediately?
d
Yes, it does. If the values were only supplied after the
collectLatest
lambda was entered, the answer would be 3 seconds.
r
Ah gotcha, bad example then. Thanks for the explanation.
d
Now that I think of it, the answer would be 2 seconds realistically.
First, we spend 1 second processing
1
, and while that's happening,
2
would arrive, be replaced by
3
, and then
3
would be processed.
The processing for
1
wouldn't be interrupted once it's started, though.
r
Nice, thanks for the explanations
🙂 1