I need some help understanding how coroutines clea...
# coroutines
c
I need some help understanding how coroutines clean up after being cancelled. I have an example :- I have a function that returns a
ReceiveChannel
, and inside that function I am starting new suspended functions. Pseudocode:
Copy code
suspend fun produceStrings(): ReceiveChannel<String> {
        return produce {
            send(suspendedFunction1())
            send(suspendedFunction2())
            send(suspendedFunction3())
        }
    }
The code that calls
produceStrings
is consuming the channel via
consumeEach
. If at some point I
cancel
the channel, I am expecting that the suspended functions inside the
produce
block are stopped. i.e. I have a breakpoint in
suspendedFunction3()
and I can see that the breakpoint is hit after I have cancelled the channel. Is this expected behaviour?
Having read some more, It might be because I was using Thread.sleep to slow down the function and thus that made the coroutine uncancellable
m
Cancellation is cooperative. The coroutine can only be cancelled at a suspension point.
The
delay
function is the suspending version of
Thread.sleep
.
👍 1