Kotlin 热流和冷流

冷流

订阅时,才发送数据。多次订阅,每个订阅都是新的数据。

热流

创建时,就发送数据。类似广播形式,订阅时,之前发送的数据不会收到。

Kotlin 冷流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
val flow1 = flow<Int> {  
repeat(10){
emit(it)
delay(1000L)
}
}
val flow2 = callbackFlow<Int> {
repeat(10){
trySend(it)
delay(1000L)
}
awaitClose{
cancel()
}
}

冷流转热流

1
2
3
Flow<>.stateIn(GlobalScope, SharingStarted.Eagerly,null)  

Flow<>.shareIn(GlobalScope, SharingStarted.Eagerly)

Kotlin 热流

1
2
3
4
5
6
7
8
val flow3 = MutableStateFlow(1)
flow3.value = 2
flow3
.onEach { value -> println("${value}") }
.launchIn(this) // 启动收集但不阻塞
flow3.value = 3

MutableSharedFlow(1)