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

lux*_*i78 1 kotlin kotlin-coroutines

我是协程/流的新手,想知道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) }
}
Run Code Online (Sandbox Code Playgroud)

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

Gle*_*val 5

您可以使用firstfirstOrNull运算符。一旦收到第一个符合条件的元素,它将停止收集:

val service = flow.firstOrNull { name == it.serviceName }
    ...
Run Code Online (Sandbox Code Playgroud)

您可以在这里first找到官方文档