Jetpact 之 LiveData

LiveData和ViewModel的关系
  • 在ViewModel中的数据发生变化是通知页面


    image.png

    当ViewModel数据发生变化通过LiveData通知View数据变化进行更新

LiveData应用:
  • 非UI线程使用postValue
  • UI线程使用setValue
class MyViewModel :ViewModel() {
    private lateinit var liveData:MutableLiveData<Int>

   fun getCurrentSecond():MutableLiveData<Int>{
        if(!this::liveData.isInitialized){
            liveData = MutableLiveData()
            liveData.value = 0
        }
        return liveData
    }
}
class Test2Activity : AppCompatActivity() {

    private var viewModel: MyViewModel? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test2)

        viewModel =
            ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(
                MyViewModel::class.java
            )
        findViewById<TextView>(R.id.textView).text = viewModel?.getCurrentSecond()?.value.toString()
        viewModel?.getCurrentSecond()?.observe(this) {
            findViewById<TextView>(R.id.textView).text = it.toString()
        }
        startTime()
    }

    private fun startTime() {
        Timer().schedule(
            object : TimerTask() {
                override fun run() {
                    viewModel?.getCurrentSecond()
                        ?.postValue((viewModel?.getCurrentSecond()?.value?.plus(1)))
                }

            },
            1000,
            1000
        )
    }
}
LiveData的优势:
  • 确保页面符合数据状态
  • 不会发生内存泄漏
  • 不会因Activity停止而导致崩溃
  • 不在需要手动处理生命周期
  • 数据始终保持最新状态
  • 适当的配置更改
  • 共享资源
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容