问题描述
arrived.observe(this,new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if(aBoolean==true){
Intent intent = new Intent(MyApplication.getAppContext(),RouteCompleteActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_up,R.anim.do_nothing);
finish();
}
}
});
Intent navIntent = new Intent(MyApplication.getAppContext(),NavigationStartActivity.class);
navIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(navIntent);
finish();
这让我回到了我的主 NavigationStartActivity,然后当我再次选择回到我原来的 RouteActivity 时,RouteCompleteActivity 还在上面吗?所以我得到 RouteCompleteActivity 而不是 RouteActivity ,然后如果我按回它去 RouteActivity ?好像它记住了一些backstack?谁能解释一下?
解决方法
我假设您使用的是来自 viewModel 或存储库的 LiveData,它会保持其价值。情况是这样的:arrived
有一个 true
值,onChanged
将被调用。下次 RouteActivity 观察到时,onChanged 将再次被调用,因为它已经有一个值,另一个 startAcrivity
将被调用。一个简单的解决方案是使用 SingleLiveEvent
代替它由谷歌很久以前创建的 link
public class SingleLiveEvent<T> extends MutableLiveData<T> {
private static final String TAG = "SingleLiveEvent";
private final AtomicBoolean mPending = new AtomicBoolean(false);
@MainThread
public void observe(LifecycleOwner owner,final Observer<T> observer) {
if (hasActiveObservers()) {
Log.w(TAG,"Multiple observers registered but only one will be notified of changes.");
}
// Observe the internal MutableLiveData
super.observe(owner,new Observer<T>() {
@Override
public void onChanged(@Nullable T t) {
if (mPending.compareAndSet(true,false)) {
observer.onChanged(t);
}
}
});
}
@MainThread
public void setValue(@Nullable T t) {
mPending.set(true);
super.setValue(t);
}
/**
* Used for cases where T is Void,to make calls cleaner.
*/
@MainThread
public void call() {
setValue(null);
}
}
它只是在设置新值时调用 onChange
。我还建议您阅读 this 文章,该文章对其进行了更深入的描述