LiveDataBus
1.基础使用
MutableLiveData<UserInfo> objectMutableLiveData = new MutableLiveData<>();
objectMutableLiveData.observe(this, new Observer<UserInfo>() {
@Override
public void onChanged(UserInfo userInfo) {
}
});
objectMutableLiveData.postValue(new UserInfo());
2.LiveDataBus:View外部调用
public class LiveDataBus<E> {
private Map<String, MutableLiveData<E>> bus;
private static LiveDataBus liveDataBus = new LiveDataBus();
private LiveDataBus() {
bus = new HashMap<>();
}
public static LiveDataBus getInstance() {
return liveDataBus;
}
public synchronized <T> MutableLiveData<T> width(String key, Class<T> type, boolean stick) {
if (!bus.containsKey(key)) {
bus.put(key, new MutableLiveData<E>());
}
return (MutableLiveData<T>) bus.get(key);
}
}
//使用
MutableLiveData<UserInfo> liveData = LiveDataBus.getInstance().width("MainActivity", UserInfo.class, true);
liveData.observe(this, new Observer<UserInfo>() {
@Override
public void onChanged(UserInfo userInfo) {
}
});
liveData.postValue(new UserInfo());