Update Coroutines 1.3.0-RC

Working version:

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

    awaitClose {
        listener.unsubscribe()
    }
}

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

Original Question

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

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

一段时间后,我想取消订阅该流.目前我做以下工作:

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() 
    }
}

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?

推荐答案

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

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

NOTE: You should call cancellable() before collect if you want your collector stop when Job is canceled.

Kotlin相关问答推荐

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

如何注入返回通用列表的转换器?

TzdbZoneRulesProvider 在 java.time 中不工作

Kotlin 如何使用其 get 函数在内部检索映射值

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

Kotlin 插件之间的区别

kotlin 如何决定 lambda 中的参数名称?

是什么让 Kotlin 中的 String 类能够使用方括号?

伴随对象在变量更改时更改它的值

Kotlin 创建snackbar

如何在 Kotlin 中传递有界通配符类型参数?

有没有办法在数据类构建时转换属性的值?

如何将 Kotlin 日期中的字符串或时间戳格式化为指定的首选格式?

如何从kotlin中的类实例化对象

Kotlin reflect proguard SmallSortedMap

指定为非null的参数在ArrayAdaper中为null

在 Kotlin 函数上使用 Mokito anyObject() 时,指定为非 null 的参数为 null

无法解决:androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1

Android:Exoplayer - ExtractorMediaSource 已弃用

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?