Thiyagu
01/03/2020, 12:56 PMproducerContext
and consumerContext
will have same CoroutineScope
?does flowScope.cancel()
make both coroutines context not to accept any more task in it?tseisel
01/03/2020, 1:20 PMproducerContext
and consumerContext
are 2 independent contexts : one is backed by one thread, the other has a pool of 2 threads.
When collecting from the flow, the code from channelFlow
will be executed on the producer thread, and each element is notified on one of the consumer threads.
Cancelling the flowScope
results in :
1. Cancelling the consumer coroutine (the one started by launchIn
)
2. Cancel collection of the flow, and therefore the block in awaitClose
it called on the producer thread.Thiyagu
01/03/2020, 1:26 PMflowScope.cancel()
is enough stop the flow and both coroutineContext will be stopped. both my context will be having the same scope?tseisel
01/03/2020, 1:55 PMJob
is an unit of work that has a lifecycle : started, stopped, cancelled.
A CoroutineDispatcher
describes how coroutines are executed and resumed. It abstracts threads away.
A CoroutineContext
is the sum of multiple properties. `Job`s and `CoroutineDispatcher`s may be part of a CoroutineContext
.
A CoroutineScope
is the primitive for structured concurrency. It simply wraps a CoroutineContext
, and cancelling a scope indirectly cancels jobs that are part of its context.
From those definitions, we deduce that :
• being based on `CoroutineDispatcher`s, both producerContext
and consumerContext
will not stop, their thread pool will still be allocated.
• Because the producer coroutine in channelFlow
is launched in the scope of its ProducerScope
, it is automatically cancelled when the flow collection is cancelled (you don't need to manually cancel the job in awaitClose
)collect
(or launchIn
in this case) will cancel any upstream operations, including the producer.channelFlow
block by replacing it with the following :
flow {
while(true) {
emit(Random.nextInt(1000)
delay(100)
}
}.buffer()
Thiyagu
01/03/2020, 2:36 PM