/
SafeCollector.kt
30 lines (24 loc) · 978 Bytes
/
SafeCollector.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.flow.internal
import kotlinx.coroutines.flow.*
import kotlin.coroutines.*
internal actual class SafeCollector<T> actual constructor(
internal actual val collector: FlowCollector<T>,
internal actual val collectContext: CoroutineContext
) : FlowCollector<T> {
// Note, it is non-capturing lambda, so no extra allocation during init of SafeCollector
internal actual val collectContextSize = collectContext.fold(0) { count, _ -> count + 1 }
private var lastEmissionContext: CoroutineContext? = null
override suspend fun emit(value: T) {
val currentContext = coroutineContext
if (lastEmissionContext !== currentContext) {
checkContext(currentContext)
lastEmissionContext = currentContext
}
collector.emit(value)
}
public actual fun release() {
}
}