简体   繁体   English

是否可以从收集的代码块中停止 flow 的收集?

[英]Is it possible to stop the flow 's collection from collect's code block?

I am a newbie in coroutine/flow and would like to know the appropriate way to close the flow from the collect 's code block when it gets the value it wanted.我是协程/流程的新手,想知道在获得所需值时从collect的代码块中关闭流程的适当方法。

The code like this:像这样的代码:

suspend fun findService(scope:CoroutineScope, context:Context, name:String) {
  val flow = getWifiDebuggingConnectDiscoveryFlow( context )
  try {
    flow.collect {
      if(name == it.serviceName)  {
        /* need to exit the collection and execute the code that follows */
      }
    }
    println("service found!")
  } catch(e: Throwable) {
    println("Exception from the flow: $e")
  }

  /* need to do something after service found */

}

private fun getWifiDebuggingConnectDiscoveryFlow(context:Context) = callbackFlow {
  val nsdManager:NsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
  val listener = object : NsdManager.DiscoveryListener {
    override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {cancel("onStartDiscoveryFailed")}
    override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {cancel("onStopDiscoveryFailed")}
    override fun onDiscoveryStarted(serviceType: String?) {}
    override fun onDiscoveryStopped(serviceType: String?) {}
    override fun onServiceLost(serviceInfo: NsdServiceInfo?) {}

    override fun onServiceFound(serviceInfo: NsdServiceInfo?) {
      if(serviceInfo==null) return
      trySend(serviceInfo)
    }
  }
  nsdManager.discoverServices(ServiceDiscovery.ADB_CONNECT_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)
  awaitClose { nsdManager.stopServiceDiscovery(listener) }
}

This problem has been bothering me for a long time, and I would appreciate any help I get.这个问题困扰了我很长时间,如果能得到任何帮助,我将不胜感激。

You can use the first or firstOrNull operators.您可以使用firstfirstOrNull运算符。 It will stop collecting as soon as the first element that complies the condition is received:一旦收到符合条件的第一个元素,它将立即停止收集:

val service = flow.firstOrNull { name == it.serviceName }
    ...

You can find first official documentation here你可以在这里找到first官方文档

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

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