如果一個activity,在onCreate的時候建立Livedata監聽,當此activity啓動兩遍的時候,會拋出Cannot add the same observer with different lifecycles異常,原因是使用了lamda表達式
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
liveData.observe(this, value-> {
....
});
}
}
使用lamda表達式建立監聽,當Activity未finish的時候,再一次啓動的時候,就會報異常,下面是拋出異常的地方:
public abstract class LiveData<T> {
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
/*********************拋出異常的地方***********************/
if (existing != null && !existing.isAttachedTo(owner)) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
owner.getLifecycle().addObserver(wrapper);
}
}
原因是在同一個類裏 使用lamda表達式 實例化的對象,竟然是同一個實例,改成原始的new
關鍵字就好了
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
liveData.observe(this,new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
}
});
}
}