简体   繁体   English

从常规 java function 向 kotlin 的流发送数据

[英]Emit data to kotlin's flow from regular java function

I have an external interface which I cannot change:我有一个无法更改的外部接口:

interface ExternalApi {
    fun onDataReceived(data: String)
}

I need to start consuming data and send it to flow .我需要开始使用数据并将其发送到flow Data order is a necessity.数据顺序是必要的。 I'd like to have a cold flow , but I couldn't find a version of cold flow with emit function, so I used hot flow + replay set to Max value as a workaround.我想要一个flow ,但我找不到带有emit function 的flow版本,所以我使用flow + 重放设置为最大值作为解决方法。 Here was my first try:这是我的第一次尝试:

class FlowProblem {
    val flow: MutableSharedFlow<String> = MutableSharedFlow(replay = Int.MAX_VALUE)

    fun startConsuming() {
        object : ExternalApi {
            override fun onDataReceived(data: String) {
                flow.emit(data)
            }
        }
    }
}

Unfortunately it doesn't work as emit function is a suspended function.不幸的是,它不起作用,因为emit function 是暂停的 function。 However this is an external interface and I cannot add suspend modifier.但是,这是一个外部接口,我无法添加挂起修饰符。 I tried to also do something like this:我也尝试做这样的事情:

override fun onDataReceived(data: String) {
    val coroutineScope = CoroutineScope(Job())
    coroutineScope.launch {
        flow.emit(data)
    }
}

but for me it's kind a silly to create new coroutine only in order to move data to flow.但对我来说,仅仅为了移动数据而创建新的协程是一种愚蠢的做法。 I'm also wondering about data order.我也想知道数据顺序。

What should I do?我应该怎么办? Maybe flow/channel is not suitable here and I should pick something another?也许流/渠道不适合这里,我应该选择另一个?

Thanks IR42, callbackFlow was exactly what I needed.感谢 IR42, callbackFlow正是我所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM