SrSouza
12/10/2020, 7:39 PMDaniele B
12/10/2020, 10:12 PMrocketraman
12/11/2020, 12:50 AMimport kotlinx.coroutines.*
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@FlowPreview
@ExperimentalCoroutinesApi
@InternalCoroutinesApi
fun <T> ConflatedBroadcastChannel<T>.wrap(): CFlow<T> = CFlow(asFlow())
@InternalCoroutinesApi
fun <T> Flow<T>.wrap(): CFlow<T> = CFlow(this)
/**
* An iOS compatible wrapper for Flow (including StateFlow). See
* * <https://github.com/JetBrains/kotlinconf-app/blob/master/common/src/iosMain/kotlin/org/jetbrains/kotlinconf/DispatcherNative.kt>
* * <https://github.com/Kotlin/kotlinx.coroutines/issues/462>
* * <https://github.com/Kotlin/kotlinx.coroutines/issues/470>
*
* and an example declaration in Kotlin native and usage from Swift here:
*
* * <https://github.com/JetBrains/kotlinconf-app/blob/33f2d4e65f470d1444c5d4b46249af8feb243d03/common/src/mobileMain/kotlin/org/jetbrains/kotlinconf/ConferenceService.kt#L278>
* * <https://github.com/JetBrains/kotlinconf-app/blob/33f2d4e65f470d1444c5d4b46249af8feb243d03/iosApp/iosApp/Components/SessionCardView.swift#L63-L65>
* * <https://github.com/JetBrains/kotlinconf-app/blob/33f2d4e65f470d1444c5d4b46249af8feb243d03/iosApp/iosApp/Components/SessionCardView.swift#L193>
*/
@InternalCoroutinesApi
class CFlow<T>(private val origin: Flow<T>): Flow<T> by origin {
fun watch(block: (T) -> Unit): Closeable {
val job = Job()
onEach {
block(it)
}.launchIn(CoroutineScope(dispatcher() + job))
return object: Closeable {
override fun close() {
job.cancel()
}
}
}
}