๐ฑ dreaming DiNO
[Android] Coroutine ์ฝ๋ฃจํด ์์ 2 - ๋ ํธ๋กํ ์ํ, async ์ฌ์ฉ ๋ณธ๋ฌธ
Android
[Android] Coroutine ์ฝ๋ฃจํด ์์ 2 - ๋ ํธ๋กํ ์ํ, async ์ฌ์ฉ
MK_____ 2023. 7. 7. 15:33suspend ํจ์ ์์ฐจ์ ์คํ
SecondFragment.kt
binding.checkBtn.setOnClickListener {
secondViewModel.exampleSuspend()
}
SecondViewModel.kt
fun exampleSuspend() {
viewModelScope.launch(Dispatchers.IO) {
val time = measureTimeMillis { // ์์์๊ฐ // ๋น๋๊ธฐ ์คํ๊ณผ ์ฝ๋ฐฑ์ ์์ฐจ์ ์ผ๋ก ๋ง๋ค์ด ์ค๋ค!
val one = doSomethingUsefulOne()
val two = doSomethingUsefulTwo()
println("The answer is ${one + two}")
}
println("Completed in $time ms")
}
}
suspend fun doSomethingUsefulOne(): Int {
println("doSomethingUsefulOne-()")
val product1 = repository.getOneProduct("1")
return product1?.id ?: -1
}
suspend fun doSomethingUsefulTwo(): Int {
println("doSomethingUsefulTwo-()")
val product2 = repository.getOneProduct("2")
return product2?.id ?: -1
}
doSomethingUsefulOne-()
doSomethingUsefulTwo-()
The answer is 3
Completed in 1651 ms
๋ฏธ๋ฆฌ ์ฐ๊ฒฐํด๋์ ๋ ํธ๋กํ์ผ๋ก Api ํธ์ถํ์ฌ ์์ฐจ์ ์ผ๋ก ์ฐํ ๋ก๊ทธ๋ฅผ ํ์ธํด๋ณด์


์ฒซ๋ฒ์งธ api๋ฅผ ํธ์ถํ๊ณ ์ ์์ ์ผ๋ก ๋๋ ๋๊น์ง ๊ธฐ๋ค๋ ธ๋ค๊ฐ ๋๋ฒ์งธ api๋ฅผ ํธ์ถํ๋ค.
Suspend ํจ์ ๋น๋๊ธฐ์ ์ผ๋ก ์คํ
async ์ฌ์ฉ
fun exampleSuspend() {
viewModelScope.launch(Dispatchers.IO) {
val time = measureTimeMillis { // ์๋ก dependency ๊ฐ ์๋ ํจ์๋ผ๋ฉด, ๋น๋๊ธฐ์ ์ผ๋ก ์คํํ์ฌ ์๊ฐ์ ์ค์ผ ์ ์๋ค
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
}
The answer is 3
Completed in 1329 ms // ์๊ฐ์์ ๋จ์ถ
๋ก๊ทธ๋ฅผ ํ์ธํด๋ณด๋ฉด api ํธ์ถํ์๋ง์ ๊ทธ ๋ค์ api ๋ฅผ ํธ์ถํ๋ค.
