从iOS收听Kotlin协程流 [英] Listen to Kotlin coroutine flow from iOS
问题描述
我已经设置了一个Kotlin Multiplatform项目,并在其上附加了 SQLDelight 数据库.它的所有设置和运行正常,因为我已经使用以下命令在android端对其进行了测试:
I have setup a Kotlin Multiplatform project and attached a SQLDelight database to it. Its all setup and running correctly as i have tested it on the android side using the following:
commonMain:
commonMain:
val backgroundColorFlow: Flow<Color> =
dbQuery.getColorWithId(BGColor.id)
.asFlow()
.mapToOneNotNull()
使用以下命令在Android项目MainActivity.kt
中触发正常:
which triggers fine in the Android projects MainActivity.kt
using:
database.backgroundColorFlow.onEach { setBackgroundColor(it.hex) }.launchIn(lifecycleScope)
但是当尝试在iOS项目应用程序委托中访问相同的调用时,我得到以下选项,并且不确定如何使用它们或将它们转换为我的BGColor
对象:
but when trying to access the same call in the iOS projects app delegate i get the following options and im unsure how to use them or convert them into my BGColor
object:
database.backgroundColorFlow.collect(collector: T##Kotlinx_coroutines_coreFlowCollector, completionHandler: (KotlinUnit?, Error?) -> Void)
有人可以帮助我如何使用它吗?
can anyone help me with how to use this?
推荐答案
因此,通过创建流程助手来解决了这个问题:
So this was resolved by creating a flow helper:
import io.ktor.utils.io.core.Closeable
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun <T> Flow<T>.asCommonFlow(): CommonFlow<T> = CommonFlow(this)
class CommonFlow<T>(private val origin: Flow<T>) : Flow<T> by origin {
fun watch(block: (T) -> Unit): Closeable {
val job = Job()
onEach {
block(it)
}.launchIn(CoroutineScope(Dispatchers.Main + job))
return object : Closeable {
override fun close() {
job.cancel()
}
}
}
}
我的backgroundColorFlow
var更新如下,以利用此帮助程序:
My backgroundColorFlow
var is update as follows to utilise this helper:
val backgroundColorFlow: CommonFlow<BGColor> =
dbQuery.getColorWithId(BGColor.id)
.asFlow()
.mapToOneNotNull()
.map { BGColor(it.name) }
.asCommonFlow()
然后我的迅捷工作方式如下:
Then my swift works as follows:
database.backgroundColorFlow.watch { color in
guard let colorHex = color?.hex else {
return
}
self.colorBehaviourSubject.onNext(colorHex)
}
和android一样:
and android like so:
database.backgroundColorFlow.watch { setBackgroundColor(it.hex) }
希望这可以帮助遇到此问题的任何人.我想将CommonFlow类转换为Flow的扩展,但是没有专有的atm,所以恕我直言,恕我直言将是一个更好的解决方案
Hope this helps anyone that comes across this. I would like to convert the CommonFlow class into an extension of Flow but don't have the know-how atm so if any could that IMHO would be a much nicer solution
这篇关于从iOS收听Kotlin协程流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!