@@ -1810,22 +1810,26 @@ import kotlinx.coroutines.experimental.selects.*
18101810
18111811### Selecting from channels
18121812
1813- Let us have two channels of strings ` fizz ` and ` buzz ` . The ` fizz ` channel produces "Fizz" string every 300 ms:
1814-
1813+ Let us have two producers of strings: ` fizz ` and ` buzz ` . The ` fizz ` produces "Fizz" string every 300 ms:
1814+
1815+ <!-- - INCLUDE .*/example-select-01.kt
1816+ import kotlin.coroutines.experimental.CoroutineContext
1817+ -->
1818+
18151819``` kotlin
1816- val fizz = produce<String >(CommonPool ) { // produce using common thread pool
1817- while (true ) {
1820+ fun fizz ( context : CoroutineContext ) = produce<String >(context ) {
1821+ while (true ) { // sends "Fizz" every 300 ms
18181822 delay(300 )
18191823 send(" Fizz" )
18201824 }
18211825}
18221826```
18231827
1824- And the ` buzz ` channel produces "Buzz!" string every 500 ms:
1828+ And the ` buzz ` produces "Buzz!" string every 500 ms:
18251829
18261830``` kotlin
1827- val buzz = produce<String >(CommonPool ) {
1828- while (true ) {
1831+ fun buzz ( context : CoroutineContext ) = produce<String >(context ) {
1832+ while (true ) { // sends "Buzz!" every 500 ms
18291833 delay(500 )
18301834 send(" Buzz!" )
18311835 }
@@ -1837,7 +1841,7 @@ other. But [select] expression allows us to receive from _both_ simultaneously u
18371841[ onReceive] [ SelectBuilder.onReceive ] clauses:
18381842
18391843``` kotlin
1840- suspend fun selectFizzBuzz () {
1844+ suspend fun selectFizzBuzz (fizz : ReceiveChannel < String >, buzz : ReceiveChannel < String > ) {
18411845 select<Unit > { // <Unit> means that this select expression does not produce any result
18421846 fizz.onReceive { value -> // this is the first select clause
18431847 println (" fizz -> '$value '" )
@@ -1849,12 +1853,14 @@ suspend fun selectFizzBuzz() {
18491853}
18501854```
18511855
1852- Let us run it seven times:
1856+ Let us run it all seven times:
18531857
18541858``` kotlin
18551859fun main (args : Array <String >) = runBlocking<Unit > {
1860+ val fizz = fizz(context)
1861+ val buzz = buzz(context)
18561862 repeat(7 ) {
1857- selectFizzBuzz()
1863+ selectFizzBuzz(fizz, buzz )
18581864 }
18591865}
18601866```
0 commit comments