我是靠谱客的博主 如意毛衣,这篇文章主要介绍Kotlin开发Android App和Java的差异8----Kotlin中使用协程Flow数据流,现在分享给大家,希望可以做个参考。

1 Flow的概念

关于流的概念,在RxJava中就有提及。数据流是可以通过异步的方式来处理一组数据,而不仅仅是单个数据的处理,而且不会阻塞主线程

2 Flow的创建和使用

Kotlin中,Flow的创建是通过flow来完成,Repository相当于是一个创造者,通过emit注射发送给消费者(UI)

复制代码
1
2
3
4
5
6
7
8
9
10
11
Repository 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
15
fun 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
16
fun 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
9
lifecycleScope.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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(99)

评论列表共有 0 条评论

立即
投稿
返回
顶部