karelpeeters
12/18/2017, 4:18 PMfun main(args: Array<String>) = runBlocking {
myFun { if (it == 10) return@myFun }
}
suspend fun myFun(call: suspend (Int) -> Unit) {
for (i in 0 until 50) {
call(i)
println(i)
}
}
, but the coroutine just keeps running. I also tried coroutineContext.cancel()
on line 2, but that doesn't work either and throws an exception.dave08
12/18/2017, 5:54 PMmyFun
and call
suspendable? Where do you really need to suspend? In the example, there's no reason to use coroutines, it might help to be more specific...karelpeeters
12/18/2017, 9:41 PMdave08
12/19/2017, 3:32 AMasync
(and I think on withTimeoutOrNull
... if so, it might also get run async and not be doing what you want unless you give it coroutineContext
as its coroutine context param...), and the runProgram
actually suspendable in the current coroutine (one of the `async`s) either when `send`ing from the channel until when the receiver is ready to get another value, or `receive`ing from the other until the `send`er is ready to send...
A side problem in your code is that it will never suspend for either, since you're using a LinkedListChannel
... the sender will never suspend and keep on filling the channels buffer, and the receiver will almost never suspend since there will always be what to get from that buffer... so if you need to suspend, you need to use a RendezvousChannel
. Otherwise, you're just using a regular linked list with backpressure handling, so you don't need suspend functions, and you could use offer
and I think pull
from the channels which are non-suspending. All this is a side point observation.
The two async
normally can be cancelled using the Deferred
they return, but in your case it could be problematic to pass that into runProgram
... you might be able to throw a CancellationException
which is not a real exception, but the normal way coroutines cancel themselves...
Good luck in learning coroutines!karelpeeters
12/19/2017, 1:56 PM