Alexjok
06/20/2019, 12:52 PMval channel = Channel<Int>(1)
fun main() = runBlocking<Unit> {
launcher().start()
test().start()
}
fun CoroutineScope.launcher() = launch(start = CoroutineStart.LAZY) {
while(isActive) {
channel.send(i)
delay(Random.nextLong(100, 6000))
}
}
fun CoroutineScope.test() = launch(start = CoroutineStart.LAZY) {
while (true) {
doSomething(channel.receive())
}
}
fun doSomething(value: Int) {
println(value)
}
Dico
06/20/2019, 1:12 PMproduce
in your producer coroutine to create the channel and manage its lifecycle.
You can have one function that creates the channel (or gets it from produce) and combines the function calls, passing the channel as a parameter instead of using global stateAlexjok
06/20/2019, 1:32 PMfun main() = runBlocking<Unit> {
val channel = Channel<Int>(1)
channel.send(1)
val producer = producer(channel)
repeat(10) { launcher(producer) }
}
fun CoroutineScope.launcher(producer: ReceiveChannel<Int>) = launch {
for(msg in producer) {
doSomething(msg)
}
}
fun CoroutineScope.producer(rec: ReceiveChannel<Int>) = produce {
for(msg in rec) send(msg)
}
fun doSomething(value: Int) {
println(value)
}
Dico
06/20/2019, 2:37 PMfun main() = runBlockingUnit {
val producer = producer()
repeat(10) { launcher(producer) }
}
fun CoroutineScope.launcher(producer: ReceiveChannelInt) = launch {
for(msg in producer) {
doSomething(msg)
}
}
fun CoroutineScope.producer(rec: ReceiveChannelInt) = produce {
repeat(1_000_000){ send(Random.nextInt()) }
}
fun doSomething(value: Int) {
println(value)
}