본문

181023(화) - Kotlin Coroutine (Channel)

Kotlin Coroutine


Channel

- deferred value는 coroutines 같의 single value transfer를 쉽게 하도록 한다.

- BlockingQueue와 매우 유사

put -> send

take -> receive


- channel instance receive하면 send했던 내용 get!


Closing and iteration over channels

- queue랑은 다르게, channel이 closed되어 no more elements are comming을 indicate 가능

- receive side에서는 for loop를 사용해서 channel element를 처리하는게 편리하다.

- conceptually close는 channel에 special close token을 보내는것과 같다.


Building channel producers

- coroutine이 elements sequence를 producing하는건 quite common pattern이다.

- 여기서는 producer-consumer pattern을 소개한다.

- channel을 parameter에 넣는방법으로 producer를 abstract할 수 있겠지만, result가 functions return되어야 한다는 common sense와 contrary

- convenient coroutine builder인 produce {...} 를 사용하면 make it easy.

- consumer side에서 produceEach를 사용하면 for loop 대체 가능


Pipelines

- pipeline은 one coroutine이 infinite stream을 producing하는 pattern

- produce { while (true) send(x++) }

- CoroutineScope extensions functions들은 모두 structured concurrency에 의존하므로 lingering global coroutines가 our application에 있는지 확인해야 한다. (?)


Prime numbers with pipeline

buildIterator 

- produce -> buildIterator

- send -> yield

- receive -> next

- ReceiveChannel -> Iterator

- channel을 사용하면 Dispatchers.Default context에서 actually use multiple CPU cores 사용 가능하다는 점


Fan-out

- multiple coroutines는 receive from same channel할 수 있으며, 이를 distributing 가능하다.

- producer를 중복으로  calling하는것은 주의해야 한다.

- for loop는 coroutines중 하나가 종료되면, 다른 coroutine이 still processing channel

- consumeEach는 정상, 비정상 종료시에 항상 underlying cannel한다.


Fan-in

- multiple coroutines은 send same channel.


Buffered channels

- 위에서 설명한 channel은 모두 buffer가 없음

- unbuffered channel은 sender and receiver가 meet (aka rendezvous) 해야 했다.

- send가 first invoked되면 suspended until receive invoked

- receive가 first invoked되면 suspended until send invoked

- Channel factory의 produce builder는 buffer size capacity optional parameter가 있다.

- similar to BlockingQueue with a capacity

- BlockingQueue의 buffer가 full되기전에  block되는것 같이, buffered channel도 suspending 되기전에 send multiple element.









































































공유

댓글