3

I am implementing Android Architecture Components. Imagine a case like the following where your Fragment is observing a LiveData to change its UI. User minimizes the app and the state is changed (in my case from the repository). So the Observer from the Fragment is not triggered with a change because the Fragment is not visible. But then, when the user comes back to the app it doesn't trigger the new state. If the state is changed again (while the Fragment is visible), the Observer receives the change. Do you know any way to force an update when fragment is visible again?

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    vm = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
    vm.getStatus()?.observe(this, Observer<MyRepository.Status> { status ->
        if (status != null) {
            when (status) {
                NONE -> setNoneUI()
                LOADING -> setLoadingUI()
                CONTENT -> setContentUI()
                ERROR -> setErrorUI()
            }
        }
    })
}
4

1 回答 1

2

LiveData实际上,您的活动应该从再次可见时接收到最新状态,如本视频中所述并在此处描述:

始终保持最新数据:如果生命周期变为非活动状态,它会在再次变为活动状态时接收最新数据。例如,后台的活动在返回前台后立即接收最新数据。

我只是在我自己的应用程序中对其进行了测试,如前所述。因此,您的应用程序中肯定存在另一个错误:您LiveData是否从存储库类中正确设置了?也许是不同的线程/postValue问题?

于 2017-11-15T18:41:21.693 回答