第一种
public static Observable<Intent> receiverObservable(final Context context, final IntentFilter intentFilter) {
return Observable.create(new Observable.OnSubscribe <Intent>() {
private BroadcastReceiver receiver;
@Override
public void call(final Subscriber <? super Intent> subscriber) {
context.registerReceiver(receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(intent);
}
}
}, intentFilter);
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
context.unregisterReceiver(receiver);
}
}));
}
});
}
第二种
public static Observable<Intent> receiverObservable2(final Context context, final IntentFilter intentFilter) {
return Observable.fromEmitter(new Action1 <Emitter <Intent>>() {
private BroadcastReceiver receiver;
@Override
public void call(final Emitter <Intent> intentEmitter) {
context.registerReceiver(receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
intentEmitter.onNext(intent);
}
}, intentFilter);
intentEmitter.setCancellation(new Cancellable() {
@Override
public void cancel() throws Exception {
context.unregisterReceiver(receiver);
}
});
}
}, Emitter.BackpressureMode.BUFFER);
}
同理我们可以将系统或者自定义的异步回调的接口转化成obsevable的方式,当然有时候回调的方法会是多个不像rxjava中提供的onNext,那么我们只能根据onNext传参来区分
网友评论