LiveData

LiveData

文章

个人总结

LiveData解决了什么问题,有什么优势?

  • LiveData具有生命周期感知能力,那么它就可以只更新处于活跃生命周期状态的应用组件的观察者。它遵循了观察者模式,LiveData通过通知Observer对象中来更新界面。
  • 观察者会绑定到Lifecycle对象,然后可以在关联对象的生命周期进入销毁状态时进行自我清理,因此可以避免内存泄漏的发生。
  • 而如果观察者的生命周期处于不活跃状态,它也不会接受任何LiveData事件。
  • 不需要手动处理生命周期。
  • 数据始终保持最新状态。即使组件的生命周期为不活跃状体,也会在进入活跃状态时接收最新数据;以及因为配置更改而重建的组件也会立即接收最新的可用数据。
  • 可以以单例模式去使用LiveData对象。

LiveData的用法?

  • 创建LiveData

    通过 LiveData实例来存储某种类型的数据,并且这通常在ViewModel类中完成

    class NameViewModel : ViewModel() {
    
        // 创建了一个存储String类型数据的LiveData对象
        val currentName: MutableLiveData<String> by lazy {
            MutableLiveData<String>()
        }
      
        // Rest of the ViewModel...
    }
    
  • 观察LiveData

    创建Observer对象,它可以控制当LiveData对象存储的数据更改时会执行的内容。当更新存储在LiveData对象中的值时,会触发所有已注册的Observer。

    class MainActivity2 : AppCompatActivity() {
    
        private lateinit var model: NameViewModel
    
        private lateinit var nameTextView: TextView
        private lateinit var button: Button
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main2)
    
            model = ViewModelProviders.of(this).get(NameViewModel::class.java)
    
            nameTextView = findViewById(R.id.content)
            button= findViewById(R.id.bt)
    
            // 创建Observer对象
            val nameObserver = Observer<String> { newName ->
                nameTextView.text = newName
            }
          
          
           //将Observer注册到LiveData上,
            model.currentName.observe(this, nameObserver)
              
              //更新LiveData对象
            button.setOnClickListener {
                val anotherName = "John Doe"
                model.currentName.setValue(anotherName)
            }
        }
    }
    
  • 更新LiveData

    如上代码的形式。

LiveData数据流设计

  • 为什么要设计LiveData数据流

    项目当中涉及的数据其实可以抽象出一个流向,这个流向指的是数据之间相互影响的关系,一个良好的数据流意味着更加清晰数据关系,更加有迹可循的数据变化,并且尽量减少对数据更新的范围,其实这也就是尽可能缩小错误情况发生时影响的范围。

  • 如何设计LiveData数据流

    根据数据的流向,尽可能缩小某个数据源变更时影响的范围,必要的时候可以把表示数据源的结构再进行细分。

原文地址:https://www.cnblogs.com/chen-ying/p/13183799.html