簡體   English   中英

所有生產者協程完成后如何關閉通道?

[英]How to close the channel after all producer coroutines are done?

考慮以下代碼:

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.*

fun main() = runBlocking<Unit> {
    val channel = Channel<String>()
    launch {
        channel.send("A1")
        channel.send("A2")
        log("A done")
    }
    launch {
        channel.send("B1")
        log("B done")
    }
    launch {
        for (x in channel) {
            log(x)
        }
    }
}

fun log(message: Any?) {
    println("[${Thread.currentThread().name}] $message")
}

原始版本的接收器協程是這樣的:

launch {
        repeat(3) {
            val x = channel.receive()
            log(x)
        }
    }

它預計頻道中只有 3 條消息。 如果我將其更改為第一個版本,那么我需要在所有生產者協程完成后關閉通道。 我怎樣才能做到這一點?

一個可能的解決方案是創建一個等待所有channel.send()完成的作業,並在該作業的invokeOnCompletion中調用channel.close()

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.*

fun main() = runBlocking<Unit> {
    val channel = Channel<String>()
    launch {
      launch {
          channel.send("A1")
          channel.send("A2")
          log("A done")
      }
      launch {
          channel.send("B1")
          log("B done")
      }
    }.invokeOnCompletion {
        channel.close()
    }
    launch {
        for (x in channel) {
            log(x)
        }
    }
}

fun log(message: Any?) {
    println("[${Thread.currentThread().name}] $message")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM