我想把一个真正的监听器包装成可观察的对象。
首先,这里是一个测试用例,对他来说一切都很好。
@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
与observate.create()相同的错误。
也许这是因为RxJava2 does not support emitting a null value这个事实。
怎么做才对?
最佳答案
您应该删除subscribeOn(Schedulers.io())
以避免在其他线程中创建PhoneStateListener
,因为在引擎盖下正试图使用mqueue为空的处理程序发送消息。只要打电话
getObservablePhoneState()
.subscribe { integer -> Log.i("", "----- subscribe onNext = " + integer) }
关于android - 将异步监听器转换/包装到Observable(RxJava2),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46332016/