๐ฑ dreaming DiNO
[Android] Coroutine ์ฝ๋ฃจํด ์์ 1 ๋ณธ๋ฌธ
Basic
SecondFragment.kt
binding.checkBtn.setOnClickListener {
secondViewModel.exampleSuspend()
}
SecondViewModel.kt
fun exampleSuspend() = runBlocking {
launch {
repeat(5) { i ->
println("Coroutine A, $i")
}
}
launch {
repeat(5) { i ->
println("Coroutine B, $i")
}
}
println("Coroutine Outer")
}
I: Coroutine Outer
I: Coroutine A, 0
I: Coroutine A, 1
I: Coroutine A, 2
I: Coroutine A, 3
I: Coroutine A, 4
I: Coroutine B, 0
I: Coroutine B, 1
I: Coroutine B, 2
I: Coroutine B, 3
I: Coroutine B, 4
launch ๊ฐ ๋จผ์ ์คํ๋์ Coroutine A ๊ฐ ๊ฐ์ฅ ๋จผ์ ์ฐํ ๊ฒ ๊ฐ์์ง๋ง,
launch๋ ์ฝ๋ฃจํด์ด ์คํ๋๊ธฐ ์ํด ์ค์ผ์ฅด๋ง์ด ๋๋ค๋ ๊ฒ์ ์์ํ ์ ์๋ค.
→ Coroutine Outer ๋จผ์ ์ฐํ๊ณ launch ๋ก ์์ฑ๋ ์ฝ๋ฃจํด์ด ์์๋๋ก ์คํ๋๋ค.
Cancellation and Timeouts
→ ์ฝ๋ฃจํด์ ์ทจ์ ๋๊ธฐ ์ํด์๋, ์ฝ๋ฃจํด์ด ํ์กฐ์ ์ด์ด์ผ ํจ
๋ฐฉ๋ฒ 1. suspend ํจ์๋ฅผ ์ํํ๋ job.cancleAndJoin()
๋ฐฉ๋ฒ 2. ์ผ๋ฐ ํจ์ ์ผ๋๋ ์ค๋จ์ด ์๋จ → isActive ์ํ ์ฒดํฌํ์ฌ ์ฝ๋ฃจํด ์ทจ์ํ๊ธฐ
fun exampleSuspend() = runBlocking {
val job = launch {
repeat(10) { i ->
println("job: I'm sleeping $i...")
delay(1000L)
}
}
delay (1500L)
println("main: I'm tired of waiting!")
// job.cancel() // ์ฝ๋ฃจํด ์ข
๋ฃ
// job.join() // job ์ํ์ด ๋๋๊ธฐ๋ฅผ ๊ธฐ๋ค๋ฆฐ๋ค
job.cancelAndJoin()
println("main: Now I can quit")
}
I: job: I'm sleeping 0...
I: job: I'm sleeping 1...
I: main: I'm tired of waiting!
I: main: Now I can quit
๋ฆฌ์์ค ํด์ ์์น
fun exampleSuspend() = runBlocking {
val job = launch {
try {
repeat(100) { i ->
println("job: I'm sleeping $i...")
delay(1000L) // suspend ํจ์์ด๊ธฐ ๋๋ฌธ์, ์ด ์ฝ๋ฃจํด์ ์ทจ์ํ๊ธฐ์ ํ์กฐ์ ์ธ ํํ
}
} finally {
// ์ฝ๋ฃจํด์ ์ทจ์ํ๋ฉด, suspend ํจ์๊ฐ ์ฌ๊ฐ๋๋ฉด์ exception ์ ๋์ง
// ์ด๊ณณ์์ ๋ฆฌ์์ค ํด์
println("job: I'm running finally")
}
}
delay (1500L)
println("main: I'm tired of waiting!")
// job.cancel() // ์ฝ๋ฃจํด ์ข
๋ฃ
// job.join() // job ์ํ์ด ๋๋๊ธฐ๋ฅผ ๊ธฐ๋ค๋ฆฐ๋ค
job.cancelAndJoin()
}
I: job: I'm sleeping 0...
I: job: I'm sleeping 1...
I: main: I'm tired of waiting!
I: job: I'm running finally
Timeouts
fun exampleSuspend() = runBlocking {
val result = withTimeoutOrNull(1300L) {
repeat(10) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
"Done"
}
println("Result is $result")
}
I: I'm sleeping 0 ...
I: I'm sleeping 1 ...
I: I'm sleeping 2 ...
I: Result is null