I was playing with Quasar in Kotlin and got to working with topics and channels. I was following some Java examples and wrote a little snippet. Unfortunately, I can't seem to get it to work. It just blocks the main thread and waits. I'm not quite sure what join is doing and wonder if that could be the issue?
public fun channelsDemo() {
val x: Val<Int> = Val()
val t: Topic<Int> = Topic()
fiber {
val c: Channel<Int> = t.subscribe(Channels.newChannel(0))
do {
val m = c.receive()
System.out.println("Channel => " + (m + x.get()))
} while (m != null)
}.join()
x.set(13)
t.send(5)
t.close()
}
edit:
public fun channelsDemo() {
val x: Val<Int> = Val()
val t: Topic<Int> = Topic()
fiber {
val c: Channel<Int> = t.subscribe(Channels.newChannel(0))
do {
val m = c.receive()
System.out.println("Channel => " + (m + x.get()))
} while (m != 40)
}
fiber {
Strand.sleep(20000)
x.set(13)
t.send(5)
t.send(21)
t.send(40)
t.close()
}
}
The join
method tells the current strand (i.e. thread or fiber) to block until the strand it is called on terminated. In this case, you wait for the fiber to terminate, but it can hardly start because you haven't sent it anything yet.
To solve, assign the fiber to some local (val f = fiber { ... }
), and only join it at the end of the program. Alternatively, don't assign it to anything and never join.