JS 与 trick 代码的运用及解析全攻略
762
2022-10-21
Android应用程序演示了Kotlin Coroutines StateFlow的使用
StateFlow - Demo
What is StateFlow?
It is a flow which emits updates to its collectors.Value can be observed by collecting values from the flow.
Implementation
ViewModel.kt:
class MainViewModel : ViewModel() { private val _countState = MutableStateFlow(0) val countState: StateFlow
MainActivity.kt:
class MainActivity : AppCompatActivity() { private val viewModel by lazy { ViewModelProvider(this)[MainViewModel::class.java] } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initCountObserver() initView() } private fun initCountObserver() { lifecycleScope.launch { viewModel.countState.collect { value -> textview_count.text = "$value" } } } private fun initView() { button_plus.setOnClickListener(::incrementCounter) button_minus.setOnClickListener(::decrementCounter) } private fun incrementCounter(view: View) { viewModel.incrementCount() } private fun decrementCounter(view: View) { viewModel.decrementCount() }}
Reference
StateFlow
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~