Kotlin Flow:如何退订/停止 [英] Kotlin Flow: How to unsubscribe/stop

查看:606
本文介绍了Kotlin Flow:如何退订/停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新协程1.3.0-RC

工作版本:

@FlowPreview
suspend fun streamTest(): Flow<String> = channelFlow {
    listener.onSomeResult { result ->
        if (!isClosedForSend) {
            offer(result)
        }
    }

    awaitClose {
        listener.unsubscribe()
    }
}

也请查阅Roman Elizarov撰写的这篇中型文章:回调和Kotlin流

Also checkout this Medium article by Roman Elizarov: Callbacks and Kotlin Flows

原始问题

我有一个流发出多个字符串:

I have a Flow emitting multiple Strings:

@FlowPreview
suspend fun streamTest(): Flow<String> = flowViaChannel { channel ->
    listener.onSomeResult { result ->
            if (!channel.isClosedForSend) {
                channel.sendBlocking(result)
            }
    }
}

一段时间后,我想取消订阅该信息流.目前,我正在执行以下操作:

After some time I want to unsubscribe from the stream. Currently I do the following:

viewModelScope.launch {
    beaconService.streamTest().collect {
        Timber.i("stream value $it")
        if(it == "someString")
            // Here the coroutine gets canceled, but streamTest is still executed
            this.cancel() 
    }
}

如果协程被取消,该流仍将执行.没有订阅者在听新值.如何取消订阅并停止 stream 函数?

If the coroutine gets canceled, the stream is still executed. There is just no subscriber listening to new values. How can I unsubscribe and stop the stream function?

推荐答案

解决方案不是取消流程,而是取消其启动范围.

A solution is not to cancel the flow, but the scope it's launched in.

val job = scope.launch { flow.collect { } }
job.cancel()

这篇关于Kotlin Flow:如何退订/停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆