runblocking 을 알려면 사실 kotlin의 coroutine 도 알아야한다. coroutine이 기초가 된후 그 위에 runblocking 구문이 있기때문.
runblocking 구문을 왜 사용하는가? runblocking구문을 통해서 새로운 coroutine 블럭을 실행하고 이 구문이 실행되고 끝날때까지 현재 쓰레드(런 블러킹을 실행한 쓰레드) 는 홀드되는 것이다.
이 구문은 일반적인 blocking 코드를 주요한 기능에서 일시적으로 사용할수 있도록 라이브러리로 구현된것인데, 예를들면 메인 함수나 테스트 함수에서 잠시! 멈춰져서 실행될수있도록 설계된 것이다.
fun <T> runBlocking(
(source)
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> T
): T
Platform and version requirements: JVM, Native
기본 CoroutineDispatcher 는 코루틴 블럭이 끝날때까지 이벤트가 실행된 함수가 멈춰지는 것이다. 그래서 CoroutineDispatcher 가 실행 문맥(context) 안에 있다면 새로운 코루틴이 실행되어야한다.(그러니까 쓰레드가 두개겠지?) 만약에 특정 디스페쳐가 다른 런블러킹 구문의 이벤트루프가 되었다면 그건 또 인보크 될것이고..(
If the specified dispatcher is an event loop of another runBlocking
, then this invocation uses the outer event loop.)
만약에 이 블록이 인터럽트 되었다면, 코루틴 잡은 실행이 취소되고 runBlocking
은 InterruptedException을 실행한다.
Parameters
context
– the context of the coroutine. The default value is an event loop on the current thread.
block
– the coroutine code.