https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Alexjok

06/20/2019, 12:52 PM
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

Dico

06/20/2019, 1:12 PM
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

Alexjok

06/20/2019, 1:32 PM
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

Dico

06/20/2019, 2:37 PM
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)
}
2 Views