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

Vlad

02/28/2020, 10:49 AM
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

diesieben07

02/28/2020, 10:54 AM
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

tseisel

02/28/2020, 12:04 PM
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

streetsofboston

02/28/2020, 12:19 PM
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

louiscad

02/28/2020, 12:20 PM
I have an
awaitCancellation()
function that returns
Nothing
and is using
suspendCancellableCoroutine<Nothing> { }
e

elizarov

02/28/2020, 2:46 PM
@louiscad I like the
awaitCancellation
name. Maybe worth adding to the library.
l

louiscad

02/28/2020, 2:47 PM
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

elizarov

02/28/2020, 2:48 PM
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

Zach Klippenstein (he/him) [MOD]

02/28/2020, 8:36 PM
So if
awaitCancellation
was added as a general function, it wouldn’t need to be defined specially for
channelFlow
anymore, right?
l

louiscad

02/28/2020, 8:43 PM
@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.)
8 Views