StateFlow?是一个状态容器式可观察数据流,可以向其收集器发出当前状态更新和新状态更新。还可通过其?value属性读取当前状态值。如需更新状态并将其发送到数据流,请为?MutableStateFlow?类的?value属性分配一个新值。
在 Android 中,StateFlow ?非常适合需要让可变状态保持可观察的类。
导入依赖:
implementation "androidx.activity:activity-ktx:1.1.0"
implementation "androidx.fragment:fragment-ktx:1.2.5"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2'
class NumberViewModel : ViewModel() {
//StateFlow与liveData很像 但能使用Flow的操作符
val number = MutableStateFlow<Int>(0)
fun increment(){
number.value++;
}
fun decrement(){
number.value--;
}
}
class NumFragment :Fragment() {
private val mViewModel by viewModels<NumberViewModel>()
private val mBinding : FragmentNumberBinding by lazy {
FragmentNumberBinding.inflate(layoutInflater)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return mBinding.root
}
override fun onStart() {
super.onStart()
mBinding.apply {
btnMinus.setOnClickListener {
mViewModel.decrement() //减
}
btnPlus.setOnClickListener {
mViewModel.increment() //加
}
}
lifecycleScope.launchWhenCreated {
mViewModel.number.collect{
//startFlow的值改变,会发送到这里更新UI
mBinding.tvNumber.text="$it "
}
}
}
}
效果演示:
|