将异步侦听器转换/包装到Observable(RxJava2)

时间:2017-09-20 21:26:14

标签: android rx-java2 listeners

我想将一个真正的侦听器包装到Observable对象中。 对于初学者来说这是一个测试用例,一切都很好。

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    getObservablePhoneState()
        // Run on a background thread
        .subscribeOn(Schedulers.io())
        // Be notified on the main thread
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(integer -> Log.i(TAG, "----- subscribe onNext = " + integer));
}

private Flowable<Integer> getObservablePhoneState() {
    return Flowable.create(emitter -> {

        Log.i(TAG, "Emitting 1");
        emitter.onNext(1);

        Log.i(TAG, "Emitting 2");
        emitter.onNext(2);

    }, BackpressureStrategy.BUFFER);
}



*** logcat ***
Emitting 1
Emitting 2
----- subscribe onNext = 1
----- subscribe onNext = 2

此代码生成错误:

private Flowable<Integer> getObservablePhoneState() {
    return Flowable.create(emitter -> {

        PhoneStateListener phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                Log.i(TAG, "onCallStateChanged = " + state);
                emitter.onNext(state);
            }
        };
        TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    }, BackpressureStrategy.BUFFER);
}

*** logcat ***
io.reactivex.exceptions.OnErrorNotImplementedException: 
Attempt to read from field 'android.os.MessageQueue 
android.os.Looper.mQueue' on a null object reference

使用Observable.create()时出现同样的错误。 也许这是因为RxJava2 does not support emitting a null value

怎么做?

1 个答案:

答案 0 :(得分:3)

您应该删除subscribeOn(Schedulers.io())以避免在另一个线程中创建PhoneStateListener,因为我们正在尝试使用mQueue为null的处理程序发送消息。只需致电

getObservablePhoneState()
     .subscribe { integer -> Log.i("", "----- subscribe onNext = " + integer) }