1
在我的Android應用我用Rxjava2,但有些奇怪的形勢出現了。Observable.create()subscribeOn和observeOn不工作
在我Disposable
我打印記錄當前線程的名稱:
//1
Observable
.create((ObservableOnSubscribe<UserModel>) e -> {
//mock io
if (phoneNumber.equals("HolyHigh") && password.equals("111111")) {
e.onNext(new UserModel());
e.onComplete();
} else {
e.onError(new RuntimeException("Error."));
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.delay(1, TimeUnit.SECONDS)
.subscribe(
r -> {
view.onLoginSuccess(new UserModel());
//test
String name = Thread.currentThread().getName();
Log.e("Thread Name", " Success Current Thread Name: " + name);
}
, e -> {
e.printStackTrace();
view.onLoginFailed(e.getMessage());
//test
String name = Thread.currentThread().getName();
Log.e("Thread Name", " Error Current Thread Name: " + name);
}
);
然後登錄:
Thread Name: Error Current Thread Name: RxComputationThreadPool-3
它看起來像observeOn和subscribeOn不工作... 爲什麼不主線程?
不過,我寫了一些簡單的...
//2
Single.timer(1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(r -> {
Log.e("Single Thread Name", "Single Thread Name: " + Thread.currentThread().getName());
CommonUtil.showToast(r + "~");
});
這個記錄:
Single Thread Name: Single Thread Name: main
哪裏是我的錯......
是的!解釋很清楚。我在'''delay()''後面移動'observeOn(AndroidSchedulers.mainThread())'',它工作!謝謝〜 – twisty