Whats the best way to efficiency suspend coroutine...
# coroutines
v
Whats the best way to efficiency suspend coroutine indefinitely?
Copy code
delay(Long.MAX_VALUE)
or
Copy code
Mutex(true).run { lock() }
or something else?
d
Copy code
suspendCoroutineUninterceptedOrReturn { COROUTINE_SUSPENDED }
But if you plan to ever resume the coroutine, you need to use
suspendCoroutineOrReturn
instead, otherwise the interceptor (dispatcher) is lost.
t
The mutex approach is quite expensive and its intent is unclear.
delay(Long.Max_VALUE)
is fine. You can also try
suspendCancellableCoroutine<Nothing> {}
đź’Ż 1
s
Using
delay(Long.MAX_VALUE)
may raise issues when unit-testing your Coroutines code. The max-value of the long may cause an overflow when calling advanceTimeBy on your test-coroutine-dispatcher, making the delay an 'negative' value. Using suspendCancellableCoroutine does not have that problem
l
I have an
awaitCancellation()
function that returns
Nothing
and is using
suspendCancellableCoroutine<Nothing> { }
e
@louiscad I like the
awaitCancellation
name. Maybe worth adding to the library.
l
I think I already had a discussion about that with you in the past @elizarov and you were like "let's see". I'll send a PR this weekend đź‘Ť
e
I’ve been hearing this question a few times already, so it looks like it needs some “out of the box” solution.
dealy(Long.MAX_VALUE)
also works great, BTW, but it does not capture the intent as well as
awaitCancellation
z
So if
awaitCancellation
was added as a general function, it wouldn’t need to be defined specially for
channelFlow
anymore, right?
l
@Zach Klippenstein (he/him) [MOD] `channelFlow`/`callbackFlow` get the
awaitClose
(not awaitCancellation) function from
ProducerScope
.
awaitCancellation
would be able to replace the no argument version, and would be usable in conjunction with a `try`/`finally` pair, but it would not be the same as the
awaitClose { ... }
overload taking a lambda. Do you think
awaitCancellation
should also have an overload accepting a lambda executed on cancellation?
đź‘Ť 1
(I'm late for the PR, I still plan on doing it this week, next Friday is my next deadline.)