1 Flow的概念
关于流的概念,在RxJava中就有提及。数据流是可以通过异步的方式来处理一组数据,而不仅仅是单个数据的处理,而且不会阻塞主线程
2 Flow的创建和使用
Kotlin中,Flow的创建是通过flow来完成,Repository相当于是一个创造者,通过emit注射发送给消费者(UI)
复制代码
1
2
3
4
5
6
7
8
9
10
11Repository suspend fun getCurrentAlarm(): Flow<Alarm> { return flow { var alarm = iWeatherDataSource.getCurrentWeather() emit(alarm) } }
Flow的使用是需要在协程中使用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15fun getCurrentWeather() : MutableLiveData<Alarm>{ val result:MutableLiveData<Alarm> = MutableLiveData<Alarm>() //在协程中使用flow viewModelScope.launch { repository.getCurrentAlarm().collect { result.postValue(it) } } return result }
3 StateFlow和SharedFlow
3.1 StateFlow
StateFlow和LiveData一样,都能够实时感知数据的变化,StateFlow也是流中的一种体现,监听数据需要在协程中使用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16fun getCurrentWeather() : MutableStateFlow<Alarm>{ //1 需要初始化赋值,LiveData不需要 var result:MutableStateFlow<Alarm> = MutableStateFlow(Alarm()) viewModelScope.launch { repository.getCurrentAlarm().collect { result.value = it // result.postValue(it) } } return result }
在Fragment中,通过lifecycleScope可以创建协程,通过collect来收集变量的数据
复制代码
1
2
3
4
5
6
7
8
9lifecycleScope.launch { newsModel.getCurrentWeather().collect { tv_show.text = it.reason } }
但是StateFlow和LiveData的不同之处在于:
(1)创建StateFlow实例,需要赋初始值,但是LiveData不需要;
(2)当View进入STOPPED的时候,LiveData.observe会自定取消注册使用方;但是StateFlow不会
3.2 SharedFlow
稍后介绍
最后
以上就是如意毛衣最近收集整理的关于Kotlin开发Android App和Java的差异8----Kotlin中使用协程Flow数据流的全部内容,更多相关Kotlin开发Android内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复