当前位置:网站首页>Kotlin-Flow common encapsulation class: the use of StateFlow
Kotlin-Flow common encapsulation class: the use of StateFlow
2022-08-03 04:32:00 【code and thinking】
Kotlin中StateFlow的使用
StateFlow 是 Flow 的实现,Is a special flow,默认的 Flow 是冷流,而StateFlow 是热流,和 LiveData 比较类似.About cold heat flow behind the issue of SharedFlow 会详细说明.
使用 StateFlow 替代 LiveData Should be at present many developers call,确实 LiveData 的功能 StateFlow 都能实现,可以说是 LiveData 的升级版.
StateFlow的特点
- 它始终是有值的.
- 它的值是唯一的.
- 它允许被多个观察者共用 (因此是共享的数据流).
- 它永远只会把最新的值重现给订阅者,这与活跃观察者的数量是无关的.
The official recommendation when exposed to UI 的状态给视图时,应该使用 StateFlow.这是一种安全和高效的观察者,专门用于容纳 UI 状态.
一、StateFlow的使用
方式一,我们自己 new 出来
一般我们再ViewModelDefined in the classification of reading and writingStateFlow
@HiltViewModel
class Demo4ViewModel @Inject constructor(
val savedState: SavedStateHandle
) : BaseViewModel() {
private val _searchFlow = MutableStateFlow("")
val searchFlow: StateFlow<String> = _searchFlow
fun changeSearch(keyword: String) {
_searchFlow.value = keyword
}
}
在ActivityWe can be like similar LiveData 一样的使用 StateFlow
private fun testflow() {
mViewModel.changeSearch("key")
}
override fun startObserve() {
lifecycleScope.launchWhenCreated {
mViewModel.searchFlow.collect {
YYLogUtils.w("value $it")
}
}
}
方式二,通过一个 冷流 Flow 转换为 StateFlow
val stateFlow = flowOf(1, 2, 3).stateIn(
scope = lifecycleScope,
// started = WhileSubscribed(5000, 1000),
// started = Eagerly,
started = Lazily,
initialValue = 1
)
lifecycleScope.launch {
stateFlow.collect {
}
}
Several important parameters of the following
- scope 共享开始时所在的协程作用域范围
- started 控制共享的开始和结束的策略
- Lazily: 当首个订阅者出现时开始,在 scope 指定的作用域被结束时终止.
- Eagerly: 立即开始,而在 scope 指定的作用域被结束时终止.
- WhileSubscribedTo specify the current don't have a subscriber after,How much time to cancel the upstream data and to specify how much time after,The data in the cache is lost,回复称initialValue的值.
- initialValue 初始值
二、替代LiveData
不管是普通的 ViewModel 观察订阅模式,在Activity中订阅,还是DataBinding的模式,我们都可以使用StateFlow来代替ViewModel
val withdrawMethod = MutableStateFlow(0)
<ImageView
android:id="@+id/iv_giro_checked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/d_15dp"
android:src="@drawable/pay_method_checked"
android:visibility="gone"
binding:isVisibleGone="@{viewModel.withdrawMethod == 1}" />
为什么我们需要用StateFlow来代替LiveData,或者说LiveData有什么缺点?
LiveData vs Flow
先上代码,Look at their usage and difference
ViewModel的代码
@HiltViewModel
class Demo4ViewModel @Inject constructor(
val savedState: SavedStateHandle
) : BaseViewModel() {
private val _searchLD = MutableLiveData<String>()
val searchLD: LiveData<String> = _searchLD
private val _searchFlow = MutableStateFlow("")
val searchFlow: StateFlow<String> = _searchFlow
fun changeSearch(keyword: String) {
_searchFlow.value = keyword
_searchLD.value = keyword
}
}
ActivityThe trigger and receive events
private fun testflow() {
mViewModel.changeSearch("key")
}
override fun startObserve() {
mViewModel.searchLD.observe(this){
YYLogUtils.w("value $it")
}
lifecycleScope.launchWhenCreated {
mViewModel.searchFlow.collect {
YYLogUtils.w("value $it")
}
}
}
You can see the basic use is almost no difference,在DataBindingThe same is can be use.So what are the differences?
They are the same place:
- 仅持有单个且最新的数据
- 自动取消订阅
- 提供「可读可写」和「仅可读」两个版本收缩权限
- 配合 DataBinding 实现「双向绑定」
相比StateFlow ,LiveData的确定:
- LiveDataIn certain scenarios will lose data
- LiveData Only in the main thread can't easily support asynchronous
- LiveData 的数据变换能力远远不如 Flow
- LiveData Sticky problem solving requires additional extension
- LiveData 多数据源的合流能力远远不如 Flow
- LiveData The default does not support image stabilization,Value does not change also will inform
这么惨,That our development whether to give upLiveData了?

恰恰不是!
If everyone is allKoltin代码开发,那么是可以用Flow,这是基于Kotlin代码,Based on coroutines realize,But now many projects or Java 语言开发的.那么LiveData还是很香的.
其二是LiveDataCosts and to learn 协程、Flow Learning as much cost,Development is the whole team,Can't say that you will be a person with,目前LiveDataThe simple learning cost is of great advantage.
We just need to use some specific scenepostValue,Such as data comparison mods scene,我们尽量使用setValue方法.
总结
If everyone's program language is Kotlin ,And team members will be Flow .So I recommend you useStateFlow 替代LiveData .如果不是,那么 LiveData 是你最好的选择.
Google also is recommended to useFlow替代LiveData.But did not say to give up LiveData .并且 LiveData 与 StateFlow 都有各自的使用场景,不需要担心 LiveData的 使用.
In this paper, we simply compare,关于StateFlow 与 SharedFlow 和LiveData The three differences and selection,后面等SharedFlowThe interpretation of the issue in detail.
Why a lot of things have to waitSharedFlow,是因为 SharedFlow 是 StateFlow 的基础,StateFlow 像是 SharedFlow 的‘青春版’.A lot of things need to finish SharedFlow Skewer the knowledge points to,期待一下.
作者:newki
链接:https://juejin.cn/post/7127082531358244900
来源:稀土掘金
边栏推荐
猜你喜欢

MySQL 入门:Case 语句很好用

2022/08/02 学习笔记 (day22) 多线程

【HMS core】【Ads Kit】华为广告——海外应用在国内测试正式广告无法展示

我将GuiLite移植到了STM32F4开发板上

path development介绍

Record some bugs encountered - when mapstruct and lombok are used at the same time, the problem of data loss when converting entity classes

工程制图点的投影练习

工程制图第九章作业

DFS对剪枝的补充

深圳线下报名|StarRocks on AWS:如何对实时数仓进行极速统一分析
随机推荐
5.回顾简单的神经网络
接口和协议
直播|StarRocks 技术内幕 :低基数全局字典优化
社交电商如何做粉丝运营?云平台怎么选择商业模式?
SM30 表维护视图数据保存前 数据校验事件
t conditional judgment statement and if loop
深圳线下报名|StarRocks on AWS:如何对实时数仓进行极速统一分析
Redis缓存雪崩、缓存穿透、缓存击穿
如何利用 Flutter 实现炫酷的 3D 卡片和帅气的 360° 展示效果
DC-5靶场下载及渗透实战详细过程(DC靶场系列)
IDEC和泉触摸屏维修HG2F-SS22V HG4F软件通信分析
DC-3靶场搭建及渗透实战详细过程(DC靶场系列)
online test paper concept
多肽介导PEG磷脂——靶向功能材料之DSPE-PEG-RGD/TAT/NGR/APRPG
Mysql如何建立索引实现语句优化
肖sir__简历
8.电影评论分类:二分类问题
Dialog manager in the fourth chapter: the dialog message loop
v-text指令:设置标签内容
好消息!北京、珠海PMP考试时间来啦