AppCompatActivity、ViewModel 和数据绑定

AppCompatActivity, ViewModel and Data Binding

试图了解 Google 的最新工具和概念:LifecycleActivity, ViewModel and Data Binding

所以想象有一个 FooActivity 扩展 AppCompatActivity(能够使用支持库)并实现 LifecycleOwner 接口(来自参考:使用 LiveData 需要):

FooActivity.kt:

class FooActivity: AppCompatActivity(), LifecycleObserver {
  ...

我们设置绑定:

  ..
  private val mBinding: by lazy {
    DataBindingUtil.setContentView<ActivityFooBinding>(this, R.layout.activity_foo)
  }
  ..

我们设置 activity 的 ViewModel,并附上我们的 barObserver(它应该观察 ViewModelbar 的变化,这只是StringsList):

  ..
  val viewModel = ViewModelProviders.of(this).get(FooViewModel::class.java)
  viewModel.getBars()?.observe(this, barObserver)
  viewModel.init() // changes bar, should trigger Observer's onChanged
  ..

最后我们定义barObserver:

  ..
  class BarObserver : Observer<List<String>> {
    override fun onChanged(p0: List<String>?) {
      Log.d("Say", "changed:")
    }
  }
  barObserver = BarObserver()
  ..

问题:

  1. 为什么 Observers onChange 从未触发?
  2. 是否应该使用 LifeCycleOwner``getLifecycle 而不是 Observer
  3. 还有其他想法吗?

编辑: 作为 reference states:

LiveData is a data holder class that can be observed within a given lifecycle. This means that an Observer can be added in a pair with a LifecycleOwner, and this observer will be notified about modifications of the wrapped data only if the paired LifecycleOwner is in active state. LifecycleOwner is considered as active, if its state is STARTED or RESUMED. An observer added via observeForever(Observer) is considered as always active and thus will be always notified about modifications. For those observers, you should manually call removeObserver(Observer).

变化中:

enter code hereviewModel.getBars()?.observe(this, barObserver)

至:

viewModel.getBars()?.observeForever(barObserver)

没有成功。 onChange 仍然没有触发。

编辑2:

FooActivity.kt:

替换为:

class FooActivity: AppCompatActivity(), LifecycleRegistryOwner{
  override fun getLifecycle(): LifecycleRegistry {
        var lifecycle = LifecycleRegistry(this)
        lifecycle.addObserver(barObserver)
        return lifecycle
    }

FooViewModel:

  ..
  private var mBar = MutableLiveData<List<String>>()
  ..
  mBar.value = listValueOf("1", "2", "3")
  ..
  fun getBar(): LiveData<List<String>>? = mBar
  ..

如果您不扩展 LifecycleActivity,那么您的 activity 应该实施 LifecycleRegistryOwner 而不是 LifecycleObserver。查看 docs.

然后你可以把它传递给liveData.observe(lifecycleOwner, observer)