Hey, I'm just starting with coroutines as well. Is...
# coroutines
k
Hey, I'm just starting with coroutines as well. Is there a way to stop a coroutine from inside? Something like this:
Copy code
fun 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.
d
Why do have and
myFun
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...
You might already know that you're running a coroutine on
async
(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!
k
First of all, thanks for your thorough reply! The order of operations doesn't matter here, since the only way the programs can influence each other is trough those channels, so they're enough as the suspension points. I saw the exception but that seamed to leak into System.err, not sure how that happened, maybe I should take another look.