Jetpack LiveData

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());
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容