https://www.youtube.com/watch?v=sk3svS_fzZM&list=PLQkwcJG4YTCQHCppNAQmLsj_jW38rU9sC&index=52
1. flow 的创建
在viewmodel中创建一个计时倒数的flow
val countDownFlow = flow<Int> {
val startValue = 10
var curValue = startValue
while (curValue > 0) {
delay(1000L)
curValue--
emit(curValue)
}
}
在compose中使用这个flow
val time by flowDemoViewModel.countDownFlow.collectAsState(10)
Text(text = time.toString())
可以看到,页面启动后,text的数字有10变到0
抛开界面,单纯的收集流
fun collectFlow() {
viewModelScope.launch {
countDownFlow.collect {time->
println("The current time is $time")
}
}
}
启动的时候开始收集
LaunchedEffect(null) {
flowDemoViewModel.collectFlow()
}
流输出

2. collect和 collectLatest 有什么区别呢?
我们在发送和接收的地方都添加上打印
//创建示例
val countDownFlow = flow<Int> {
val startValue = 10
var curValue = startValue
while (curValue > 0) {
delay(1000L)
curValue--
println("The current emit $curValue")
emit(curValue)
}
}
fun collectFlow() {
println("The current time collect")
viewModelScope.launch {
countDownFlow.collectLatest {time->
println("The current time is start $time")
delay(1500)
println("The current time is end $time")
}
}
}
先用collect,看下打印效果
countDownFlow.collect {}
数据发送端是一秒发送一个,但是接收地方需要1.5秒处理,但是使用collect的话,整个数据还是按顺序下来的<
Kotlin Flow的创建、操作与特点

最低0.47元/天 解锁文章
5585

被折叠的 条评论
为什么被折叠?



