我开始为Android学习Rx
,我收到一个错误。这是我的代码:
在我的Subscriber
我打印以记录当前线程名称:
Subscriber<Integer> integerSubscriber = new Subscriber<Integer>() {
// ... onCompleted, onError
@Override
public void onNext(Integer s) {
Log.e("RX", "threadName " + getCurrThreadName());
}
};
这里我想在后台运行代码并从mainThread中的Observable获取数据:
ArrayList list = new ArrayList();
list.add(...) // creating data list
Observable.from(list)
.map(TransformFunc.getTransformer())
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.from(executor))
.subscribe(integerSubscriber);
...
其他代码: static String getCurrThreadName(){ return Thread.currentThread()。getName(); }
static class TransformFunc implements Func1<String, Integer> {
private static TransformFunc instance;
static TransformFunc getTransformer() {
... // return instance
@Override
public Integer call(@NonNull String s) {
...
TimeUnit.SECONDS.sleep(4);
Log.e("RX", "threadName " + getCurrThreadName());
...
return s.length();
}
}
但是当我在设备上运行此代码时,我会看到白屏5-10秒,这在日志中:
12-02 16:34:39.374 26086-26086/com.shevart.fitnessnotes E/RX: threadName main
12-02 16:34:39.378 26086-26180/com.shevart.fitnessnotes E/RX: threadName pool-1-thread-2
12-02 16:34:43.375 26086-26086/com.shevart.fitnessnotes E/RX: threadName main
12-02 16:34:43.379 26086-26216/com.shevart.fitnessnotes E/RX: threadName pool-1-thread-3
12-02 16:34:47.376 26086-26086/com.shevart.fitnessnotes E/RX: threadName main
12-02 16:34:47.396 26086-26253/com.shevart.fitnessnotes E/RX: threadName pool-1-thread-4
12-02 16:34:51.376 26086-26086/com.shevart.fitnessnotes E/RX: threadName main
12-02 16:34:51.398 26086-26292/com.shevart.fitnessnotes E/RX: threadName pool-1-thread-5
为什么onNext()
在地图之前调用call()
之前?
答案 0 :(得分:1)
你想观察主线程,而不是其他方式。
.subscribeOn(Schedulers.from(executor))
.observeOn(AndroidSchedulers.mainThread())