Introduction
코루틴으로 실행된 작업의 결과를 수신하는 방법은??
기존에는 Deferred로 결과값을 감싼 다음 await()를 통해 해당 값이 수신될 때까지 기다려야 한다.
suspend fun main() {
val deferred: Deferred<String> = CoroutineScope(Dispatchers.IO).async {
"Async Result"
}
val result = deferred.await()
println(result)
}
withContext
이렇기 때문에 withContext를 이용해 비동기 작업을 순차 코드처럼 작성할 수 있다.
suspend fun main() {
val result: String = withContext(Dispatchers.IO) {
"Async Result"
}
println(result)
}