使用containAsFlow

问题描述

我有一个函数,该函数调用broadcastChannel.createSubscription返回一个ReceiveChannel

fun subscribe(name: String): ReceiveChannel<String> {
    return mybroadcastChannels[name]?.openSubscription()
}

如果我要在整个应用程序中使用ReceiveChannel来管理生命周期,这似乎很简单(调用ReceiveChannel.cancel)。但是在调用函数中,我需要使用流操作,因为不赞成使用通道操作(例如RecieveChannel.map

//Not allowed due to deprecated map call
fun getCars(name: String): ReceiveChannel<Cars> = subscribe(name)
                                                     .map{ deserializetoCar(it) }

推荐的解决方案似乎是:

//Uses flow operation
fun getCars(name: String): Flow<Cars> =  subscribe(name)
                                            .collectAsFlow()
                                            .map{ deserializetoCar(it) }

问题是一旦使用collectAsFlow,对我来说不清楚RecieveChannel应该如何关闭

取消在我称为Flow.collect的coroutinescope时会取消对我的broadcastChannel订阅吗? (我尝试过的实验似乎并未表明这一点)我是否需要提供一种方法关闭Flow旁边的通道?

fun getCars(name: String): Pair<Flow<Cars>,Closeable> {
       val channel = subscribe(name)
       val flow = channel 
                      .collectAsFlow()
                      .map{ deserializetoCar(it) }
       return flow to Closeable{ 
              channel.cancel()
       }
}

//Used as:
val (flow,closeable) = getCars("FactoryA")

    flow.collect{ car ->
       println(car)
       if(doneUsingFlow){
           closeable.close()
       }
    } 

drinkAsFlow是否会以某种方式结束对生命周期的管理?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)