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

richodemus

09/05/2018, 2:49 PM
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

marstran

09/05/2018, 2:52 PM
Instead of delaying, you should use an actor. You can send a message to it when you meet your criteria.
r

richodemus

09/05/2018, 2:55 PM
This question is specific to delay or something that handles very similar
I want to suspend my coroutine and unsuspend it on command
m

marstran

09/05/2018, 2:55 PM
Yes, and that it exactly what an actor is useful for.
s

Seri

09/05/2018, 2:56 PM
You can cancel the entire job, and catch the cancellation in a try/catch block
m

marstran

09/05/2018, 3:00 PM
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

bj0

09/05/2018, 3:39 PM
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

gildor

09/06/2018, 1:44 AM
+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

richodemus

09/06/2018, 8:53 AM
Thanks
3 Views