RXjava在2016年大放异彩,如果大家已经在项目中使用了Rxjava,可以尝试用Rxbus来替代Eventbus(Rxbus也是基于观察者模式),这样就不需要再引入其他的依赖库了!
话不多说,我们直接上代码:
public class RxBus { private static volatile RxBus mInstance; private final Subject bus; public RxBus() { bus = new SerializedSubject<>(PublishSubject.create()); } /** * 单例模式RxBus * * @return */ public static RxBus getInstance() { RxBus rxBus2 = mInstance; if (mInstance == null) { synchronized (RxBus.class) { rxBus2 = mInstance; if (mInstance == null) { rxBus2 = new RxBus(); mInstance = rxBus2; } } } return rxBus2; } /** * 发送消息 * * @param object */ public void post(Object object) {bus.onNext(object);} /** * 接收消息 * * @param eventType * @param <T> * @return */ public <T> Observable<T> toObserverable(Class<T> eventType) { return bus.ofType(eventType); } }定义一个单例的Rxbus类,确保线程的安全。
public class MainActivity extends AppCompatActivity { private TextView tv; private Subscription rxSbscription; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); rxSbscription = RxBus.getInstance().toObserverable(StudentEvent.class) .subscribe(new Action1在主Activity里面进行订阅,这里需要注意的是在Activity销毁的时候记得解绑哦!不然发生内存泄漏,这个锅我可不背!() { @Override public void call(StudentEvent studentEvent) { tv.setText("id:" + studentEvent.getId() + " name:" + studentEvent.getName()); } }); tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent it=new Intent(); it.setClass(MainActivity.this,MainActivity2.class); startActivity(it); } }); } @Override protected void onDestroy() { if (!rxSbscription.isUnsubscribed()){ rxSbscription.unsubscribe(); } super.onDestroy(); } }
public class MainActivity2 extends AppCompatActivity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); RxBus.getInstance().post(new StudentEvent("123","小明")); } }在事件产生的源头执行post方法,Rxbus接收到消息以后会自动的把消息转发给订阅者!
到这里一个简单的Rxbus就实现啦!