본문 바로가기

코틀린

Coroutine

(조금 더 글을 보충해야할 필요가 있다.)
코틀린의 코루틴은 suspending functions 는 future나 promise보다 훨씬 좋다.
kotlin 공식문서 피셜 비동기 동작에서 더욱 안전하고 에러도 적은 추상화를 제공해준다고 한다.
 
뭐.. 위의 자료를 참고하면 될듯.
 
kotlin의 공식문서를 참고해서 공부한 내용을 정리한 것이다. 아래는 공식문서 링크.

Your first coroutine

코루틴은 일시정지가 가능한 구성요소다. 스레드 개념과 비슷한데, 다른 코드를 동시실행하는게 가능하기 때문이다.
코루틴은 어떠한 스레드에도 속해있지 않다.
한 스레드에서 실행을 일시 중단했다가 다른 스레드에서 다시 시작할 수 있습니다.
 
(코루틴이 스레드를 동작시키거나 멈추게 하는게 아니다. 코루틴 자체가 스레드에서 중지했다가 다시 재개하는게 가능하다는 말이다.)
 
코루틴은 가벼운 스레드라고도 생각할 수 있지만, 스레드와 사용하는데 있어서 결정적인 몇가지 차이가 존재한다.
 
아래 코드는 무려 공식문서의 샘플 코드다.
fun main() = runBlocking { // this: CoroutineScope
launch { // launch a new coroutine and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello") // main coroutine continues while a previous one is delayed
}
실행결과
Hello
world!
 
 
launch 키워드
launch 키워드는 corutine builder 이다. 나머지 코드(launch 밖에 있는 코드)와 동시에 새 코루틴을 시작하며, 이 코루틴은 독립적으로 계속 작동한다. 그러니까 위의 결과에서 Hello 부터 출려된거다.
 
 
delay 키워드
delay is a special suspending function. It suspends the coroutine for a specific time. Suspending a coroutine does not block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.
delay는 특별한 일시정지 키워드다. 이 키워드는 코루틴을 잠시동안 일시정지 시켜준다.
코루틴을 멈추는게 스레드를 block하지는 않지만, 다른 코루틴 동작할 수 있게 도와주고 실행되고 있던 스레드를 코루틴에서 사용할 수 있게 도와준다.
 
 
runBlocking 키워드
runBlocking is also a coroutine builder that bridges the non-coroutine world of a regular fun main() and the code with coroutines inside of runBlocking { ... } curly braces. This is highlighted in an IDE by this: CoroutineScope hint right after the runBlocking opening curly brace.
 
runBlocking은 또한 코루틴 빌더로, 일반 main()이나 runBlocking { ... } 중괄호로 묶습니다.
runBlocking 오른쪽에 this:CoroutineScope로 IDE에 의해서 강조 표시된다.
 
If you remove or forget runBlocking in this code, you'll get an error on the launch call, since launch is declared only on the CoroutineScope:
 
위 코드 스니펫에서 runBlocking 을 기입하지 않는다면, launch 를 호출하는 시점에 에러가 발생할 것이고, launch 는 오직 CoroutineScope 에서만 선언이 가능하다.
 
 
The name of runBlocking means that the thread that runs it (in this case — the main thread) gets blocked for the duration of the call, until all the coroutines inside runBlocking { ... } complete their execution. You will often see runBlocking used like that at the very top-level of the application and quite rarely inside the real code, as threads are expensive resources and blocking them is inefficient and is often not desired.