Kotlin Coroutine #2



reference: 

https://hellsoft.se/simple-asynchronous-loading-with-kotlin-coroutines-f26408f97f46





 Coroutine Context

이전 블로그에서 했던 launch {}는 임의의 thread의 coroutine에서 작업을 수행합니다. 만약 작업이 수행될 coroutine을 명시하고 싶다면 어떻게 해야할까요. 여기서 제공되는 것이 coroutine context입니다.


 launch with context

아래 예제에서는 content resolver로부터 어떤 이미지를 불러온 후, view에 반영하는 작업입니다.

당연히 이미지를 불러오는 작업은 disk IO이기 때문에 main thread에서는 피하는 게 좋겠죠.

val job = launch(Background) {
val
uri = Uri.withAppendedPath(imagesBaseUri, imageId.toString())
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver,
launch(UI) {
imageView.setImageBitmap(bitmap)
}
}

launch(Background)에서 Background는 무엇일까요? 

바로 CoroutineContext입니다. 

아래처럼 만들어 주면 됩니다. 2개의 fixed size를 갖는 thread pool로부터 CoroutineContext를 가져왔습니다. 이름은 "bg"네요.

internal val Background = newFixedThreadPoolContext(2, "bg")


그렇다면 아래의 UI는 무엇인가요? 네, 물론 Android의 main thread입니다. 애초에 이렇게 제공을 해주네요. 선언은 아래와 같이 돼있었습니다.

val UI = HandlerContext(Handler(Looper.getMainLooper()), "UI")


Conclusion

Thread나 Executor 등을 통해 concurrent programming을 하는 것이 Java에서는 아주 일반적이지만, Kotlin에서는 다른 방식을 제안하려고 하는 것 같습니다. Coroutine은 light-weight thread로 설명할 수 있으며, block 대신 suspend를 하기 때문에 thread에 비해 switching 비용이 매우 적습니다. Continuation Passing Style을 통해 그것이 가능하다고 합니다.

 여기에서 참고한 글을 정리했습니다.


Q. Coroutine vs thread, 언제 어떤 것을 사용해야 하나?

A. Coroutine는 다른 작업을 기다리는 용도의 비동기 작업을, thread는 CPU-intensive한 작업을 할 때 사용하면 된다.


Q. Light-weight thread라는 설명은 적절치 않아 보인다, 왜냐면 coroutine은 thread pool로 부터 thread를 가져와서 그위에 실행을 하니까. 차라리 "task"라는 설명이 더 와닿지 않느냐? (Thread 위의 Runnable 정도의 의미인 것 같네요)

A. Light-weight thread라는 표현은 표면상의 의미고, 개발자 본인이 보기에 따라 thread도 마찬가지 이듯 다른 의미가 될 수 있을 것 같다.


Q. Coroutine이 thread와 비슷하다면, 서로 다른 coroutine 간에 공유되는 상태들에 대한 동기화 작업이 필요 할 것 같다.

A. Coroutine에서는 가급적이면 가변한 공유 상태를 가지기를 추천하지 않는다. 


'programming > android' 카테고리의 다른 글

기본적인 메모리 관리  (0) 2018.03.06
Splash 화면 구성하기  (3) 2018.02.20
Kotlin Coroutines #1  (1) 2018.01.27
Tools로 xml layoyt의 preview 제대로 표시하기  (0) 2018.01.22
Kotlin Standard Functions  (0) 2018.01.22

+ Recent posts