RxBus---使用RxAndroid2.0实现RxBus

RxBus实现

1 添加Gradle:
//RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.4'
2 添加RxBus类:
public class RxBus {
private static volatile RxBus mInstance;
private final Subject subject = PublishSubject.create().toSerialized();
private Disposable dispoable;


private RxBus() {
}

public static RxBus getInstance() {
    if (mInstance == null) {
        synchronized (RxBus.class) {
            if (mInstance == null) {
                mInstance = new RxBus();
            }
        }
    }
    return mInstance;
}


/**
 * 发送事件
 * @param object
 */
public void send(Object object) {
    subject.onNext(object);
}


/**
 * @param classType
 * @param 
 * @return
 */
public  Observable toObservale(Class classType) {
    return subject.ofType(classType);
}


/**
 * 订阅
 * @param bean
 * @param consumer
 */
public void subscribe(Class bean, Consumer consumer) {
    dispoable = toObservale(bean).subscribe(consumer);
}

/**
 * 取消订阅
 */
public void unSubcribe(){
    if (dispoable != null && dispoable.isDisposed()){
        dispoable.dispose();
    }

}
 
 

}

3 添加监听
 RxBus.getInstance().subscribe(String.class, new Consumer() {
        @Override
        public void accept(String path) throws Exception {
                        
        }
 });
4 发送监听事件:
 RxBus.getInstance().send("发送事件");
5 在退出Activity(Fragment)时,取消监听:
 RxBus.getInstance().unSubcribe();

你可能感兴趣的:(RxBus---使用RxAndroid2.0实现RxBus)