当前位置:网站首页>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
来源:稀土掘金
边栏推荐
猜你喜欢
随机推荐
Shell编程的条件语句
Jmeter 模拟多用户登录的两种方法
富瑞宣布战略交易,以简化运营,持续专注于打造领先的独立全服务型全球投行公司
社交电商如何做粉丝运营?云平台怎么选择商业模式?
好消息!北京、珠海PMP考试时间来啦
修饰生物素DIAZO-生物素-PEG3-DBCO|重氮-生物素-三聚乙二醇-二苯基环辛炔
工程水文学知识点
接口测试框架实战(二)| 接口请求断言
肖sir__自动化面试题
接口测试框架实战(三)| JSON 请求与响应断言
UV 裂解的生物素-PEG2-叠氮|CAS:1192802-98-4生物素接头
在线密码生成工具推荐
SM30 表维护视图数据保存前 数据校验事件
WinForm的控件二次开发
关于#sql#的问题,如何解决?
记录一些遇见的bug——mapstruct和lombok同时使用时,转换实体类时数据丢失问题
多肽介导PEG磷脂——靶向功能材料之DSPE-PEG-RGD/TAT/NGR/APRPG
工程水文学试题库
浏览器监听标签页关闭
MySql 创建索引