[안드로이드 ] 안드로이드 공부 5일차 동기코드 비동기코드
요약
앱에서 동시에 작업하기 위해 Kotlin 코루틴
코루틴을 사용하면 코드블록의 실행을 정지했다가 나중에 다시 시작할수 있으면 그동아닁 다른 작업을 진행할수 있다.
import kotlinx.coroutines.*
fun main() {
runBlocking {
println("Weather forecast")
delay(1000)
println("Sunny")
}
}
runBlocking()은 동기식 람다 블록내 모든 작업을 완료할때가지 프프로그램이 반환되지 않는다 -> 모든 작업이 끝난후 동작
정지함수 suspend
import kotlinx.coroutines.*
fun main() {
runBlocking {
println("Weather forecast")
printForecast()
}
}
suspend fun printForecast() {
delay(1000)
println("Sunny")
}
비동기 코드 launch()
import kotlin.system.*
import kotlinx.coroutines.*
fun main() {
val time = measureTimeMillis {
runBlocking {
println("Weather forecast")
launch {
printForecast()
}
launch {
printTemperature()
}
}
}
println("Execution time: ${time / 1000.0} seconds")
}
...
위에 두 방식은 두 태스크가 모두 완료되었을 때 통합 날씨 보고를 표시하려는 경우에는 launch()를 사용하는 현재 접근 방식으로는 충분하지 않습
출처
https://developer.android.com/codelabs/basic-android-kotlin-compose-coroutines-kotlin-playground?hl=ko&continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-compose-unit-5-pathway-1%3Fhl%3Dko%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-compose-coroutines-kotlin-playground#1
댓글남기기