"
我希望我创建的observable在非创建线程执行. 并每subscribe一次, 排队执行一次. 代码如下
public void test(){
Log.d(TAG, "test() called");
Observable<SerialSignal> dd = Observable.fromCallable(new Callable<SerialSignal>() {
@Override
public SerialSignal call() throws Exception {
Thread.sleep(2000);
Log.d(TAG, "call() called" + System.currentTimeMillis()/1000L);
return null;
}
});
Observable<SerialSignal> d = Observable.create(new ObservableOnSubscribe<SerialSignal>() {
@Override
public void subscribe(ObservableEmitter<SerialSignal> emitter) throws Exception {
Thread.sleep(2000);
Log.d(TAG, "subscribe() called" + System.currentTimeMillis()/1000L);
emitter.onNext(null);
}
});
d.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
d.subscribe(new Observer<SerialSignal>() {
@Override
public void onNext(SerialSignal serialSignal) {
Log.i(TAG, "onNext: subscriber 1" +System.currentTimeMillis() /1000L );
}
//省了 onError onComplete 等
});
d.subscribe(new Observer<SerialSignal>() {
@Override
public void onNext(SerialSignal serialSignal) {
Log.i(TAG, "onNext: 112 " + System.currentTimeMillis() /1000L);
}
});
结果test() called 和 call() 都在主线程执行;而且observer的onnext 不执行.
请问哪里写错了吗. 我希望 called 在新线程执行, onNext在Android 主线程执行
"
emitter.onNext(null);改为emitter.onNext(new SerialSignal());
参考源码ObservableCreate$CreateEmitter,onNext若为null,走onError
@Override public void onNext(T t) { if (t == null) { onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); return; } if (!isDisposed()) { observer.onNext(t); } }
至于call不在子线程是因为你没赋值
d = d.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
"版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。