RxBus的简单使用

1、添加库的依赖,顺便把ButterKinfe添加一下,偷个懒哈哈

    implementation 'com.jakewharton:butterknife:8.7.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'io.reactivex:rxjava:1.2.1'

2、新建RxBus类,不多说,这个自己从网上找一下

public class RxBus {
    private static volatile RxBus defaultInstance;

    private final Subject<Object, Object> bus;
    
    public RxBus() {
        bus = new SerializedSubject<>(PublishSubject.create());
    }
    // 单例RxBus
    public static RxBus getDefault() {
        if (defaultInstance == null) {
            synchronized (RxBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new RxBus();
                }
            }
        }
        return defaultInstance ;
    }
    // 发送一个新的事件
    public void post (Object o) {
        bus.onNext(o);
    }
    // 接受消息
    public <T> Observable<T> toObservable (Class<T> eventType) {
        return bus.ofType(eventType);

    }
}

3、创建需要发送的事件类,我们要传一个city名字过去

public class CityEvent {
    private String id;
    private String cityName;

    public CityEvent(String id, String cityName) {
        this.id = id;
        this.cityName = cityName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
}

4、发送事件,我们就设定在第二个activity的点击事件中了

 RxBus.getDefault().post(new CityEvent("001","北京市"));

5、在MainActivity中接受事件

 mSubscription = RxBus.getDefault().toObservable(CityEvent.class)
                .subscribe(new Action1<CityEvent>() {
                    @Override
                    public void call(CityEvent cityEvent) {
                        text1.setText("添加城市成功,收到了ActivityTwo传来的城市名称"+ cityEvent.getCityName());
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });

6、最后不要忘了取消订阅哦,防止内存泄漏

 @Override
    protected void onDestroy() {
        if (!mSubscription.isUnsubscribed()){
            mSubscription.unsubscribe();
        }
        super.onDestroy();
    }

看看结果

               

总结

RxBus的简单用法,方便同学们查询

小Demo地址https://github.com/pengboboer/RxBusTest

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值