RxJava已经渐渐走进了程序员的日常生活,用习惯了EventBus的Coder哥决定用Rxjava的思想来实现一个Rxbus,用于替代EventBus。闲话少说,直接上代码,欢迎批评指正。
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
/**
* 类描述:RxBus,时间事件总线
*/
public class RxBus {
private final Subject<Object, Object> bus;
private RxBus() {
bus = new SerializedSubject<>(PublishSubject.create());
}
public static RxBus getInstance() {
return SingletonHolder.mInstance;
}
// 采用内部类的方式实现单例,线程安全
private static class SingletonHolder {
private static final RxBus mInstance = new RxBus();
}
public synchronized <T> Observable<T> toObservable(Class<T> eventType) {
return bus.ofType(eventType);
}
// 发送一个事件
public void post(Object content) {
bus.onNext(content);
}
}
使用方式:
public class CenterListFragment extends Fragment {
private RecyclerView mRecyclerView;
private List<Movie> mMovieList = new ArrayList<>();
private RecyclerViewAdapter mAdapter;
private Subscription mSubscription;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initRxBus();
}
/**
* 在onCreate或是onResume中注册相应的监听事件
*/
private void initRxBus() {
mSubscription = RxBus.getInstance().toObservable(IEvent.class).subscribe(new Action1<IEvent>() {
@Override
public void call(IEvent event) {
if (event instanceof DownloadFinishEvent) {
Log.d("##!##", "CenterFragment接收到事件");
return;
}
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
// TODO: 处理异常
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRecyclerView = (RecyclerView) inflater.inflate(R.layout.list_fragment, container, false);
return mRecyclerView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRecyclerView.setLayoutManager(new LinearLayoutManager(mRecyclerView.getContext()));
mAdapter = new RecyclerViewAdapter(getActivity(), mMovieList);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onDestroy() {
super.onDestroy();
mSubscription.unsubscribe(); //反注册RxBus,防止内存泄漏
}
}
IEvent.java
/**
* 类描述:事件接口
*/
public interface IEvent {
}
DownloadFinishEvent.java
/**
* 类描述:下载结束事件
*/
public class DownloadFinishEvent implements IEvent {
}