본문 바로가기
프로그래밍 놀이터/Kotlin, Coroutine

[coroutine] runBlocking 에 대해 알아보자

by 돼지왕 왕돼지 2023. 1. 9.
반응형

 

-

runBlocking 은 새로운 coroutine 을 수행하면서 현재 thread 를 interrupt 가능한 상태로 block 시킨다. 그리고 이 block 은 coroutine 이 종료될때까지 유지된다.

 

-

이 함수는 coroutine 안에서는 사용되지 않아야 한다. (should not)

runBlocking 함수는 main 함수 또는 test 에서, blocking style 이면서, suspending style 로의 넘어가기 위한 bridge 의 역할로 사용되도록 디자인 되었다.

 

-

만약 다른 context 가 지정이 된다면, 지정된 context 에서 coroutine 이 수행되고, runBlocking 을 호출한 thread 는 block 된다.

 

-

runBlocking 에서 발생하는 에러는 바깥쪽에서 try-catch 로 잡을 수 있다.

 

-

그럼 runBlocking 에 defaultHandler 를 주면 동작할까?

val exHandler = CoroutineExceptionHandler{ ctx, th -> 
	Log.e("cklee", "exception caught! $th")
}
runBlocking(exHandler) {
    delay(500)
    throw RuntimeException("die die!")
}

안타깝게도? 그러나 당연하게도? exceptionHandler 에 exception 이 catch 되지 못하고 crash 가 난다.

runBlocking 은 coroutine builder 가 아니라 일반 함수이기 때문!

 

-

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html

 

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html

 

kotlin.github.io

 

 

반응형

댓글