본문 바로가기

전체 글55

(Coroutine) 5. Scope 1. GlobalScope GlobalScope는 어디에도 속하지 않는 Scope이다. 이전 포스팅에서 살펴보았던 예제들에서 사용되던 Scope는 다른 코루틴에 의해 만들어지고 그에 따라 계층적인 성격을 가지고 있었다. 지금 살펴볼 GlobalScope는 원래부터 존재하는 전역적인 Scope이다. 따라서, 계층적으로 관리되지 않는다. suspend fun printRandom() { delay(500L) println(Random.nextInt(0, 500)) } @OptIn(DelicateCoroutinesApi::class) fun main() { val job = GlobalScope.launch(Dispatchers.IO) { launch { printRandom() } } Thread.sleep.. 2022. 11. 1.
(Kotlin) runCatching, Result 1. runCatching runCatching은 Kotlin 1.3 표준 라이브러리에 추가된 예외 처리에 효과적인 inline function이다. 일반적으로, 안드로이드 진영에서 Coroutine과 함께 사용할 때 예외 처리에 효과적이며 Google 샘플 프로젝트에서도 runCatching을 활용한 예외 처리가 많은 만큼 Google에서 권장하는 방식이다. runCatching의 내부 구현은 아래와 같다. // Result#runCatching public inline fun runCatching(block: () -> R): Result { return try { Result.success(block()) } catch (e: Throwable) { Result.failure(e) } } // Re.. 2022. 10. 28.
(Coroutine) 4. CoroutineContext, Dispatcher 1. CoroutineContext 우리는 지금까지의 포스팅을 통해 코루틴은 항상 CoroutineContext 상에서 실행되는 것을 알고있다. 그렇다면 CoroutineContext는 어떻게 구현되어 있을까? // CoroutineContext.kt public interface CoroutineContext { public operator fun get(key: Key): E? public fun fold(initial: R, operation: (R, Element) -> R): R public operator fun plus(context: CoroutineContext): CoroutineContext = { ... } public fun minusKey(key: Key): CoroutineCo.. 2022. 9. 14.
(Coroutine) 3. async 1. suspend 함수의 순차적 수행 아래 예시를 통해 suspend 함수를 순차적으로 수행해보자. suspend fun getRandom1(): Int { delay(1000L) return Random.nextInt(0, 500) } suspend fun getRandom2(): Int { delay(1000L) return Random.nextInt(0, 500) } fun main() = runBlocking { val elapsedTime = measureTimeMillis { val value1 = getRandom1() val value2 = getRandom2() println("$value1 + $value2 = ${value1+value2}") } println(elapsedTime).. 2022. 9. 14.