작성일 22.03.24

Flow ?

코틀린에서 제공되는 Cold 비동기 스트림.

Rx와 많이 비교된다.

기존 코루틴의 Channel은 Hot 비동기 스트림.

사용 예시

// 선언
val integers: Flow<Int> = **flow {**   // FlowCollector<Int> 라는 scope block 이 생긴다. 
		for (i in 1..10) {
				delay(100)
				**emit(i)**
		}
**}**

// 사용
launch {
		integers.**collect** { it: Int ->
				doSomething(it)
		}
}

1) Flows are Cold

fun foo(): Flow<Int> = flow {
		println("Flow started")
		for (i in 1..3) {
				***delay(100)**
				**emit(i)***
		}
}

launch {
		println("Calling foo")
		val flow = foo()
		println("Calling collect")
		***flow.collect { println(value) }***
		println("Calling collect again")
		***flow.collect { println(value) }***
}

# 실행결과
--------------------
Calling foo
Calling collect
Flow started
1
2
3
Calling collect again
Flow started
1
2
3
--------------------

Flow 는 collect 연산자 호출 시점에 동작하는 Cold stream 이다.

( = subscribe 시점에 동작하는 Observable)

collect 와 emit 은 suspend function 이다.

참고 : 위 스니펫에서 Bold 표기한 라인들은 blocking 되지 않고 suspend 된다. 코루틴의 delay() 는 Thread.sleep() 과는 다르게, suspend 되어 동작한다.