Android onPause 后的 LiveData Observer
Android LiveData Observer after onPause
接下来的问题是,我订阅了 activity 中的 LiveData
更改,这是我第一次在观察者中获取所有数据,但是当我开始另一个 activity 并且然后return到这个,观察者不叫。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainMenuViewModel.class);
observeViewModel();
}
@Override
protected void onResume() {
super.onResume();
viewModel.loadUserEntry();
}
public void observeViewModel() {
viewModel.getUser().observe(this, userEntry -> {
// Do some code
});
}
这是我的 ViewModel 的代码
void loadUserEntry() {
disposable.add(userRepository.getUser()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(user::setValue, Throwable::printStackTrace));
}
public LiveData<UserEntry> getUser() {
return user;
}
所以我进行了测试,并且一直在订阅,我有用户值,然后我将这个值设置到 LiveData。
如果有人能提供帮助,我将不胜感激。谢谢
看看段落 "Observe LiveData objects":
Generally, LiveData delivers updates only when data changes, and only to active observers. An exception to this behavior is that observers also receive an update when they change from an inactive to an active state. Furthermore, if the observer changes from inactive to active a second time, it only receives an update if the value has changed since the last time it became active.
我在你的情况下,只要 activity 在 backstack 中,视图模型就会存在。它导致 LiveData
持有 UserEntry
的实例,当你回到这个 activity 并调用 loadUserEntry()
它加载等于(甚至相同)的 UserEntry
实例.加载的实例与前一个相同 -> LiveData
不重新交付它。
接下来的问题是,我订阅了 activity 中的 LiveData
更改,这是我第一次在观察者中获取所有数据,但是当我开始另一个 activity 并且然后return到这个,观察者不叫。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainMenuViewModel.class);
observeViewModel();
}
@Override
protected void onResume() {
super.onResume();
viewModel.loadUserEntry();
}
public void observeViewModel() {
viewModel.getUser().observe(this, userEntry -> {
// Do some code
});
}
这是我的 ViewModel 的代码
void loadUserEntry() {
disposable.add(userRepository.getUser()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(user::setValue, Throwable::printStackTrace));
}
public LiveData<UserEntry> getUser() {
return user;
}
所以我进行了测试,并且一直在订阅,我有用户值,然后我将这个值设置到 LiveData。
如果有人能提供帮助,我将不胜感激。谢谢
看看段落 "Observe LiveData objects":
Generally, LiveData delivers updates only when data changes, and only to active observers. An exception to this behavior is that observers also receive an update when they change from an inactive to an active state. Furthermore, if the observer changes from inactive to active a second time, it only receives an update if the value has changed since the last time it became active.
我在你的情况下,只要 activity 在 backstack 中,视图模型就会存在。它导致 LiveData
持有 UserEntry
的实例,当你回到这个 activity 并调用 loadUserEntry()
它加载等于(甚至相同)的 UserEntry
实例.加载的实例与前一个相同 -> LiveData
不重新交付它。