플로우 완료처리하기
예제 75: 명령형 finally 블록
완료를 처리하는 방법 중의 하나는 명령형의 방식으로 finally 블록을 이용하는 것입니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun simple(): Flow<Int> = (1..3).asFlow()
fun main() = runBlocking<Unit> {
    try {
        simple().collect { value -> println(value) }
    } finally {
        println("Done")
    }
}  
예제 76: 선언적으로 완료 처리하기
onCompletion 연산자를 선언해서 완료를 처리할 수 있습니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun simple(): Flow<Int> = (1..3).asFlow()
fun main() = runBlocking<Unit> {
    simple()
        .onCompletion { println("Done") }
        .collect { value -> println(value) }
}
예제 77: onCompletion의 장점
onCompletion은 종료 처리를 할 때 예외가 발생되었는지 여부를 알 수 있습니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun simple(): Flow<Int> = flow {
    emit(1)
    throw RuntimeException()
}
fun main() = runBlocking<Unit> {
    simple()
        .onCompletion { cause -> if (cause != null) println("Flow completed exceptionally") }
        .catch { cause -> println("Caught exception") }
        .collect { value -> println(value) }
}