
A coroutine is an instance of a suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one.
coroutine은 suspendable(지연 가능한) computation들의 객체이다. thread와 비슷하지만 분명 thread와는 다르다.
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
}
이는 kotlin 공식문서에서 보여주는 하나의 코드다. 해당 코드를 살펴보면 다음과 같다.
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의 경우 CoroutineScope과 동일한 역할을 해준다(?)
Q -> 왜 coroutine builder인데 CoroutineScope처럼 쓸 수 있는가?
launch is a coroutine builder. It launches a new coroutine concurrently with the rest of the code, which continues to work independently. That's why Hello has been printed first.
launch는 새로운 coroutine을 기존 코드와 함께 독립적으로 동시에 실행 가능한 형태로 만들어준다.
-> launch/async의 경우 오로지 coroutineScope 안에서만 선언 가능하다.
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.
'launch' and 'async' coroutine builders returning 'Job' and 'Deferred light-weight futures' with cancellation support;
코드를 입력하세요
-> 반드시 function이 반환되면 coroutine도 종료되어야 한다.
Coroutine은 thread와 비슷하지만 thread는 아니다.[1]
kotlin은 kotlinx.coroutine과 같은 라이브러리 형태로 사용 가능하다. kotlin의 standard library에 포함되어 있지 않다.
이건 다음 글에서
댓글로 많이 남겨주세요~