134

GitHub - JeremyLiao/LiveDataBus: Android消息总线,基于LiveData,具有生命周期感知...

 5 years ago
source link: https://github.com/JeremyLiao/LiveDataBus
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

LiveDataBus

Android消息总线,基于LiveData,具有生命周期感知能力

使用方法

依赖

依赖Android Architecture Components,具体可参见gradle文件build.gradle

示例及Demo

订阅消息

  • observe模式 生命周期感知,不需要手动取消订阅
LiveDataBus.get()
	.with("key_name", String.class)
	.observe(this, new Observer<String>() {
	    @Override
	    public void onChanged(@Nullable String s) {
	       
	    }
	});
  • observeForever模式 需要手动取消订阅
LiveDataBus.get()
	.with("key_name", String.class)
	.observeForever(observer);
LiveDataBus.get()
	.with("key_name", String.class)
	.removeObserver(observer);

发送消息

  • set模式 订阅者会在当前线程收到消息
LiveDataBus.get().with("key_name").setValue(value);
  • post模式 订阅者会在主线程收到消息
LiveDataBus.get().with("key_name").postValue(value);

简单的Demo可参见:LiveDataBusDemo.java

原理

LiveDataBus的实现原理可参见作者在美团技术博客上的博文:Android消息总线的演进之路:用LiveDataBus替代RxBus、EventBus


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK