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

Tristan Caron

11/04/2017, 2:09 PM
Yes, but I cannot do

http://reactivex.io/documentation/operators/images/S.PublishSubject.png

h

hydrakecat

11/07/2017, 2:34 PM
I’m new to channels but guess something like this?
Copy code
fun main(args: Array<String>) = runBlocking<Unit> {
  val broadcast = ArrayBroadcastChannel<Int>(10)
  launch(CommonPool) {
    broadcast.consumeEach { i -> println("channel-0:$i") }
  }
  broadcast.offer(1)
  broadcast.offer(2)
  launch(CommonPool) {
    broadcast.consumeEach { i -> println("channel-1:$i") }
  }
  broadcast.offer(3)
  broadcast.offer(4)
  broadcast.close()
}
t

Tristan Caron

11/07/2017, 2:45 PM
This is the result
Copy code
./AppKt
channel-0:2
channel-0:3
channel-0:4

Process finished with exit code 0
I tried this but not doing what I want either.
Copy code
fun main(args: Array<String>) = runBlocking<Unit> {
    val broadcast = BroadcastChannel<Int>(10)

    launch {
        broadcast.openSubscription().use {
            for (value in it) {
                println(value)
            }
        }
    }

    broadcast.offer(1)
    broadcast.offer(2)

    launch {
        broadcast.openSubscription().use {
            for (value in it) {
                println(value)
            }
        }
    }

    broadcast.offer(3)
    broadcast.offer(4)

}
h

hydrakecat

11/07/2017, 2:51 PM
Sorry. It seems the result depends on the timings. How about this?
Copy code
fun main(args: Array<String>) = runBlocking<Unit> {
  val broadcast = ArrayBroadcastChannel<Int>(10)
  val job1 = launch(CommonPool) {
    broadcast.consumeEach { i -> println("channel-0:$i") }
  }
  broadcast.offer(1)
  broadcast.offer(2)
  val job2 = launch(CommonPool) {
    broadcast.consumeEach { i -> println("channel-1:$i") }
  }
  broadcast.offer(3)
  broadcast.offer(4)
  broadcast.close()
  job1.join()
  job2.join()
}
Note I am not making sure
boradcast.consumeEach
is called before
broadcast.offer(1)
so
1
might not be printed.
t

Tristan Caron

11/08/2017, 8:46 AM
It's working thank you. The problem now is when we did offer 10 elements (in this exemple). The channel close automatically. How I can prevent it?
Int.MAX_VALUE
is not a valid answer I think 😛
h

hydrakecat

11/08/2017, 10:19 AM
Well, I have no idea 🙄 I will dig into it.