Select 표현식(Select expression, 실험적)

Select 표현식(Select expression, 실험적)

Select 표현식은 여러 일시 중단 함수를 동시에 기다리다가, 그중 먼저 준비되는 것 하나를 선택할 수 있게 해 줘요.

출처: Kotlin 공식 문서

본문

채널에서 선택하기(Selecting from channels)

문자열을 만드는 생산자 두 개, fizzbuzz가 있다고 해 볼게요. fizz는 500ms마다 "Fizz" 문자열을 만듭니다:

fun CoroutineScope.fizz() = produce<String> {
    while (true) { // sends "Fizz" every 500 ms
        delay(500)
        send("Fizz")
    }
}

그리고 buzz는 1000ms마다 "Buzz!" 문자열을 만들어요:

fun CoroutineScope.buzz() = produce<String> {
    while (true) { // sends "Buzz!" every 1000 ms
        delay(1000)
        send("Buzz!")
    }
}

receive 일시 중단 함수를 쓰면 두 채널 중 하나에서만 받을 수 있어요. 하지만 select 표현식을 쓰면 onReceive 절을 통해 두 채널에서 동시에 받을 수 있습니다:

suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
    select<Unit> { // <Unit> means that this select expression does not produce any result 
        fizz.onReceive { value ->  // this is the first select clause
            println("fizz -> '$value'")
        }
        buzz.onReceive { value ->  // this is the second select clause
            println("buzz -> '$value'")
        }
    }
}

이걸 일곱 번 실행해 볼게요:

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*

fun CoroutineScope.fizz() = produce<String> {
    while (true) { // sends "Fizz" every 500 ms
        delay(500)
        send("Fizz")
    }
}

fun CoroutineScope.buzz() = produce<String> {
    while (true) { // sends "Buzz!" every 1000 ms
        delay(1000)
        send("Buzz!")
    }
}

suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
    select<Unit> { // <Unit> means that this select expression does not produce any result 
        fizz.onReceive { value ->  // this is the first select clause
            println("fizz -> '$value'")
        }
        buzz.onReceive { value ->  // this is the second select clause
            println("buzz -> '$value'")
        }
    }
}

fun main() = runBlocking<Unit> {
//sampleStart
    val fizz = fizz()
    val buzz = buzz()
    repeat(7) {
        selectFizzBuzz(fizz, buzz)
    }
    coroutineContext.cancelChildren() // cancel fizz & buzz coroutines
//sampleEnd        
}

이 코드의 결과는 다음과 같아요:

fizz -> 'Fizz'
buzz -> 'Buzz!'
fizz -> 'Fizz'
fizz -> 'Fizz'
buzz -> 'Buzz!'
fizz -> 'Fizz'
fizz -> 'Fizz'

닫힘에서 선택하기(Selecting on close)

selectonReceive 절은 채널이 닫히면 실패하고, 그 결과 해당 select는 예외를 던져요. 채널이 닫혔을 때 특정 동작을 수행하려면 onReceiveCatching 절을 사용할 수 있습니다. 다음 예시는 select가 선택된 절의 결과를 반환하는 표현식이라는 것도 보여줘요:

suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
    select<String> {
        a.onReceiveCatching { it ->
            val value = it.getOrNull()
            if (value != null) {
                "a -> '$value'"
            } else {
                "Channel 'a' is closed"
            }
        }
        b.onReceiveCatching { it ->
            val value = it.getOrNull()
            if (value != null) {
                "b -> '$value'"
            } else {
                "Channel 'b' is closed"
            }
        }
    }

"Hello" 문자열을 네 번 만드는 채널 a와 "World"를 네 번 만드는 채널 b로 이걸 사용해 볼게요:

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*

suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
    select<String> {
        a.onReceiveCatching { it ->
            val value = it.getOrNull()
            if (value != null) {
                "a -> '$value'"
            } else {
                "Channel 'a' is closed"
            }
        }
        b.onReceiveCatching { it ->
            val value = it.getOrNull()
            if (value != null) {
                "b -> '$value'"
            } else {
                "Channel 'b' is closed"
            }
        }
    }
    
fun main() = runBlocking<Unit> {
//sampleStart
    val a = produce<String> {
        repeat(4) { send("Hello $it") }
    }
    val b = produce<String> {
        repeat(4) { send("World $it") }
    }
    repeat(8) { // print first eight results
        println(selectAorB(a, b))
    }
    coroutineContext.cancelChildren()  
//sampleEnd      
}    

이 코드의 결과는 꽤 흥미로워서 더 자세히 분석해 볼게요:

a -> 'Hello 0'
a -> 'Hello 1'
b -> 'World 0'
a -> 'Hello 2'
a -> 'Hello 3'
b -> 'World 1'
Channel 'a' is closed
Channel 'a' is closed

여기서 몇 가지 관찰할 점이 있어요. 먼저, select첫 번째 절에 편향(bias) 되어 있어요. 여러 절이 동시에 선택 가능할 때 그중 첫 번째 절이 선택되죠. 여기서는 두 채널이 계속 문자열을 만들어내므로, select에서 첫 번째 절인 a 채널이 이깁니다. 다만 버퍼 없는 채널(unbuffered channel)을 쓰고 있기 때문에 a는 자신의 send 호출에서 때때로 일시 중단되어 b도 보낼 기회를 얻어요.

두 번째 관찰 점은, 채널이 이미 닫혀 있으면 onReceiveCatching이 즉시 선택된다는 것입니다.

보내기에서 선택하기(Selecting to send)

Select 표현식에는 onSend 절이 있는데, 선택의 편향된 특성과 결합하면 아주 유용해요. 소비자들이 주 채널을 따라가지 못할 때 값을 side 채널로 보내는 정수 생산자의 예시를 작성해 볼게요:

fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> {
    for (num in 1..10) { // produce 10 numbers from 1 to 10
        delay(100) // every 100 ms
        select<Unit> {
            onSend(num) {} // Send to the primary channel
            side.onSend(num) {} // or to the side channel     
        }
    }
}

소비자는 각 숫자를 처리하는 데 250ms가 걸리는 꽤 느린 소비자예요:

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*

fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> {
    for (num in 1..10) { // produce 10 numbers from 1 to 10
        delay(100) // every 100 ms
        select<Unit> {
            onSend(num) {} // Send to the primary channel
            side.onSend(num) {} // or to the side channel     
        }
    }
}

fun main() = runBlocking<Unit> {
//sampleStart
    val side = Channel<Int>() // allocate side channel
    launch { // this is a very fast consumer for the side channel
        side.consumeEach { println("Side channel has $it") }
    }
    produceNumbers(side).consumeEach { 
        println("Consuming $it")
        delay(250) // let us digest the consumed number properly, do not hurry
    }
    println("Done consuming")
    coroutineContext.cancelChildren()  
//sampleEnd      
}

그럼 어떻게 되는지 볼게요:

Consuming 1
Side channel has 2
Side channel has 3
Consuming 4
Side channel has 5
Side channel has 6
Consuming 7
Side channel has 8
Side channel has 9
Consuming 10
Done consuming

Deferred 값 선택하기(Selecting deferred values)

Deferred 값은 onAwait 절로 선택할 수 있어요. 임의의 지연 후 deferred 문자열 값을 반환하는 async 함수부터 시작해 볼게요:

fun CoroutineScope.asyncString(time: Int) = async {
    delay(time.toLong())
    "Waited for $time ms"
}

임의의 지연을 가진 것들 12개를 시작해 볼게요:

fun CoroutineScope.asyncStringsList(): List<Deferred<String>> {
    val random = Random(3)
    return List(12) { asyncString(random.nextInt(1000)) }
}

이제 main 함수는 그것들 중 첫 번째가 완료되기를 기다리고, 아직 활성 상태인 deferred 값의 개수를 셉니다. 여기서 select 표현식은 Kotlin DSL이라는 사실을 활용했어요. 그래서 임의의 코드로 절을 제공할 수 있죠. 이 경우에는 deferred 값 리스트를 반복하면서 각 deferred 값에 대한 onAwait 절을 제공합니다:

import kotlinx.coroutines.*
import kotlinx.coroutines.selects.*
import java.util.*
    
fun CoroutineScope.asyncString(time: Int) = async {
    delay(time.toLong())
    "Waited for $time ms"
}

fun CoroutineScope.asyncStringsList(): List<Deferred<String>> {
    val random = Random(3)
    return List(12) { asyncString(random.nextInt(1000)) }
}

fun main() = runBlocking<Unit> {
//sampleStart
    val list = asyncStringsList()
    val result = select<String> {
        list.withIndex().forEach { (index, deferred) ->
            deferred.onAwait { answer ->
                "Deferred $index produced answer '$answer'"
            }
        }
    }
    println(result)
    val countActive = list.count { it.isActive }
    println("$countActive coroutines are still active")
//sampleEnd
}

출력은 다음과 같아요:

Deferred 4 produced answer 'Waited for 128 ms'
11 coroutines are still active

Deferred 값 채널에 대해 전환하기(Switch over a channel of deferred values)

deferred 문자열 값의 채널을 소비하고, 받은 각 deferred 값을 다음 deferred 값이 채널로 오거나 채널이 닫힐 때까지만 기다리는 채널 생산자 함수를 작성해 볼게요. 이 예시는 onReceiveCatchingonAwait 절을 같은 select에 함께 넣습니다:

fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> {
    var current = input.receive() // start with first received deferred value
    while (isActive) { // loop while not cancelled/closed
        val next = select<Deferred<String>?> { // return next deferred value from this select or null
            input.onReceiveCatching { update ->
                update.getOrNull()
            }
            current.onAwait { value ->
                send(value) // send value that current deferred has produced
                input.receiveCatching().getOrNull() // and use the next deferred from the input channel
            }
        }
        if (next == null) {
            println("Channel was closed")
            break // out of loop
        } else {
            current = next
        }
    }
}

테스트하려고, 지정된 시간 후에 지정된 문자열로 해소되는 간단한 async 함수를 사용할게요:

fun CoroutineScope.asyncString(str: String, time: Long) = async {
    delay(time)
    str
}

main 함수는 switchMapDeferreds의 결과를 출력하는 코루틴을 시작하고, 여기에 몇 가지 테스트 데이터를 보냅니다:

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
    
fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> {
    var current = input.receive() // start with first received deferred value
    while (isActive) { // loop while not cancelled/closed
        val next = select<Deferred<String>?> { // return next deferred value from this select or null
            input.onReceiveCatching { update ->
                update.getOrNull()
            }
            current.onAwait { value ->
                send(value) // send value that current deferred has produced
                input.receiveCatching().getOrNull() // and use the next deferred from the input channel
            }
        }
        if (next == null) {
            println("Channel was closed")
            break // out of loop
        } else {
            current = next
        }
    }
}

fun CoroutineScope.asyncString(str: String, time: Long) = async {
    delay(time)
    str
}

fun main() = runBlocking<Unit> {
//sampleStart
    val chan = Channel<Deferred<String>>() // the channel for test
    launch { // launch printing coroutine
        for (s in switchMapDeferreds(chan)) 
            println(s) // print each received string
    }
    chan.send(asyncString("BEGIN", 100))
    delay(200) // enough time for "BEGIN" to be produced
    chan.send(asyncString("Slow", 500))
    delay(100) // not enough time to produce slow
    chan.send(asyncString("Replace", 100))
    delay(500) // give it time before the last one
    chan.send(asyncString("END", 500))
    delay(1000) // give it time to process
    chan.close() // close the channel ... 
    delay(500) // and wait some time to let it finish
//sampleEnd
}

이 코드의 결과입니다:

BEGIN
Replace
END
Channel was closed

더 알아보기