Notice
Recent Posts
Recent Comments
Link
ยซ   2025/04   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐ŸŒฑ dreaming DiNO

[Android] Coroutine ์ฝ”๋ฃจํ‹ด ์˜ˆ์ œ2 - ๋ ˆํŠธ๋กœํ• ์ˆ˜ํ–‰, async ์‚ฌ์šฉ ๋ณธ๋ฌธ

Android

[Android] Coroutine ์ฝ”๋ฃจํ‹ด ์˜ˆ์ œ2 - ๋ ˆํŠธ๋กœํ• ์ˆ˜ํ–‰, async ์‚ฌ์šฉ

MK_____ 2023. 7. 7. 15:33

suspend ํ•จ์ˆ˜ ์ˆœ์ฐจ์  ์‹คํ–‰

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 ๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.