美文网首页首页投稿(暂停使用,暂停投稿)
Android如何用Rxjava监听BroadcastRecei

Android如何用Rxjava监听BroadcastRecei

作者: 逃跑的计划中 | 来源:发表于2017-07-16 12:53 被阅读0次

    第一种

        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传参来区分

    相关文章

      网友评论

        本文标题:Android如何用Rxjava监听BroadcastRecei

        本文链接:https://www.haomeiwen.com/subject/olptkxtx.html