Skip to content

Instantly share code, notes, and snippets.

@posth2071
Created April 13, 2020 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save posth2071/3331f44f38632731e47c199389c63eb1 to your computer and use it in GitHub Desktop.
Save posth2071/3331f44f38632731e47c199389c63eb1 to your computer and use it in GitHub Desktop.
/* CoroutineScope 확장함수 produceSquares 선언
* : ReceiveChannel<Int>는 produce의 반환 인스턴스
* : produce{} 블록 내부가 송신자(Sender)가 됨
*/
fun CoroutineScope.produceSquares(): ReceiveChannel<Int> = produce {
// 1~10까지 배수의 값을 전달
for (i in 1..10) send(i * i)
}
fun main() = runBlocking {
// ReceiverChannel<Int> 인스턴스 반환, squares == ReceiverChannel
val squares = produceSquares()
// for-loop문 역할을 하는 학장함수(consumeEach 사용)
squares.consumeEach { println(it) } // 채널을 통해 받은 값 출력
println("Suqares running Done!")
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
// 실행 결과(Result Value)
// 1
// 4
// 9
// 16
// 25
// 36
// 49
// 64
// 81
// 100
// Suqares running Done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment