当前位置:网站首页>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
来源:稀土掘金
边栏推荐
猜你喜欢
随机推荐
c语言结构体中的冒泡排序
MySql 创建索引
肖sir__面试就业课___数据库
【Harmony OS】【FAQ】鸿蒙问题合集1
工程制图点的投影练习
SkiaSharp 之 WPF 自绘 五环弹动球(案例版)
工程制图-齿轮
在竞争白热化的电商行业,链动2+1为什么还有企业在用
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
mysql bool blind
直播|StarRocks 技术内幕 :低基数全局字典优化
MediaRecorder录制屏幕时在部分机型上报错prepare failed:-22
12.机器学习基础:评估机器学习模型
8.电影评论分类:二分类问题
肖sir___面试就业课程____性能测试
path development介绍
【Harmony OS】【ARK UI】ETS 上下文基本操作
接口测试框架实战 | 流程封装与基于加密接口的测试用例设计
1.一个神经网络示例
【Harmony OS】【ARK UI】ets使用startAbility或startAbilityForResult方式调起Ability