Is there a way to "wake up" a coroutine that is cu...
# coroutines
r
Is there a way to "wake up" a coroutine that is currently suspended due to having called
delay
so like this:
Copy code
launch {
   println("This is called right away")
   delay(1, YEARS)
   println("I want this to happen when a criteria is met")
}

if(criteria) {
  cancelDelay()
}
m
Instead of delaying, you should use an actor. You can send a message to it when you meet your criteria.
r
This question is specific to delay or something that handles very similar
I want to suspend my coroutine and unsuspend it on command
m
Yes, and that it exactly what an actor is useful for.
s
You can cancel the entire job, and catch the cancellation in a try/catch block
m
You can do this with an actor:
Copy code
val ch = actor<Int> {
    println("This is called right away")

    // Suspends until there's a message on the channel
    val ping = channel.receive()

    println("I want this to happen when a criteria is met")
}

runBlocking {
    delay(1000)
    if (criteria) {
        ch.send(0)
    }
}
1
b
yea, if you want to delay until told to continue, a
Channel
fits best. An
actor
is one way to use a channel
if you only need to do it once, a
CompletableDeferred
is also an option
g
+1 to actor solution. But it’s not exactly what original code does: do something after delay. But you can easily implement this by running additional coroutine that trigger action with delay, like:
Copy code
actor<Int> {
    println("This is called right away")
   launch(coroutineContext) {
       delay(1, YEARS)
       send(someActorData)
   }
  val ping = channel.receive()

    println("I want this to happen when a criteria is met")
}
👍 1
r
Thanks