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

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

我是 coroutine/flow 的新手,想知道在 collect 的代码块获得所需值时关闭流的适当方法。

代码如下:

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

这个问题困扰了我很长时间,如果能得到任何帮助,我将不胜感激。

您可以使用 firstfirstOrNull 运算符。只要收到第一个符合条件的元素就会停止收集:

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

你可以找到first官方文档here