<lambda>null1 package kotlinx.coroutines.flow.internal
2 
3 import kotlinx.coroutines.*
4 import kotlinx.coroutines.channels.*
5 import kotlinx.coroutines.flow.*
6 import kotlinx.coroutines.internal.*
7 import kotlinx.coroutines.intrinsics.*
8 import kotlin.coroutines.*
9 import kotlin.coroutines.intrinsics.*
10 import kotlinx.coroutines.flow.internal.unsafeFlow as flow
11 
12 /**
13  * Creates a [CoroutineScope] and calls the specified suspend block with this scope.
14  * This builder is similar to [coroutineScope] with the only exception that it *ties* lifecycle of children
15  * and itself regarding the cancellation, thus being cancelled when one of the children becomes cancelled.
16  *
17  * For example:
18  * ```
19  * flowScope {
20  *     launch {
21  *         throw CancellationException()
22  *     }
23  * } // <- CE will be rethrown here
24  * ```
25  */
26 internal suspend fun <R> flowScope(@BuilderInference block: suspend CoroutineScope.() -> R): R =
27     suspendCoroutineUninterceptedOrReturn { uCont ->
28         val coroutine = FlowCoroutine(uCont.context, uCont)
29         coroutine.startUndispatchedOrReturn(coroutine, block)
30     }
31 
32 /**
33  * Creates a flow that also provides a [CoroutineScope] for each collector
34  * Shorthand for:
35  * ```
36  * flow {
37  *     flowScope {
38  *         ...
39  *     }
40  * }
41  * ```
42  * with additional constraint on cancellation.
43  * To cancel child without cancelling itself, `cancel(ChildCancelledException())` should be used.
44  */
scopedFlownull45 internal fun <R> scopedFlow(@BuilderInference block: suspend CoroutineScope.(FlowCollector<R>) -> Unit): Flow<R> =
46     flow {
47         flowScope { block(this@flow) }
48     }
49 
50 private class FlowCoroutine<T>(
51     context: CoroutineContext,
52     uCont: Continuation<T>
53 ) : ScopeCoroutine<T>(context, uCont) {
childCancellednull54     override fun childCancelled(cause: Throwable): Boolean {
55         if (cause is ChildCancelledException) return true
56         return cancelImpl(cause)
57     }
58 }
59