GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
GlobalScope라는 CoroutineScope에서 CoroutineBuilder인 launch
를 통해 Coroutine을 만들었다.
runBlocking { // start main coroutine (blocks thread)
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L)
println("World!")
}
println("Hello,") // main coroutine continues here immediately
delay(2000L) // delaying for 2 seconds to keep JVM alive
}
val job = GlobalScope.launch { // launch a new coroutine and keep a reference to its Job
delay(1000L)
println("World!")
}
println("Hello,")
job.join() // wait until child coroutine completes
join()
으로 non-blocking 하는 방식으로 job
의 완료까지 wait 시킬 수 있다.runBlocking {
launch { // launch a new coroutine in the scope of runBlocking
delay(1000L)
println("World!")
}
println("Hello,")
}
runBlocking {
launch {
delay(200L)
println("Task from runBlocking")
}
coroutineScope { // Creates a coroutine scope
launch {
delay(500L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // This line will be printed before the nested launch
}
println("Coroutine scope is over") // This line is not printed until the nested launch completes
}
suspend
키워드를 붙여야한다.GlobalScope.launch { // Global Scope!!
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
위 코드를 실행하면 어디서 실행했든간에 앱이 꺼지지 않는한 동작할 것이다. (별도 캔슬 등 안하면)
앞서 몇개 들었던 발표들 때문인지 공식문서 첫 페이지라서 그런지 내용은 쉬웠다.