I have a case where I need subscribe to the channe...
# coroutines
a
I have a case where I need subscribe to the channel and do some work with the data from this channel when it come. Data is coming from another coroutine at different time intervals. I have a code, how i can do it better?
Copy code
val 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)
}
d
There seems to be no point lazily starting the coroutines. You can make use
produce
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 state
a
Hm, but if i follow this advice i need every time create channel with one parameter and send channel as parameter to launchprocessor or etc. In my case i send data from another coroutineScope and its not a producer, just simple scope. You mean something like this?
Copy code
fun 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)
}
d
Copy code
fun 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)
}