I´ve got the following code:
Observable.timer(AppConstants.SEND_LOCATIONS_INTERVAL_IN_MINUTES, TimeUnit.MINUTES)
.observeOn(Schedulers.newThread())
.serialize()
.retry()
.subscribe(new Action1<Long>() {
public void call(Long _) {
new SendCoordinatesToServerTask().execute();
}
},
new Action1<Throwable>() {
public void call(Throwable error) {
mLog.error(error, "SEND_LOCATIONS_FAILED", );
}
});
And i get the following error message
... Exception Ljava/lang/RuntimeException; thrown while initializing Landroid/os/AsyncTask;
我想这是一个线程问题(某种垃圾收集),因为AsyncTask没有运行也没有实例化。当我持有对实例化AsyncTask的引用并且仅从订阅中调用.execute时,它可以工作。
我知道合乎逻辑的做法是不要在订阅中使用AsyncTask 。我正处于从经常性 AsyncTask 迁移的过程中。后来我将发送逻辑重构为非 AsyncTask 类,一切都很好。
我只是好奇为什么这首先不起作用。是因为 Timer 在 Async 任务运行之前就结束了吗?即OnNext在任务之前结束,是否通过在OnComplete上结束计时器线程?
但我真正想要并最终做到的是:
CoordinatesToServerSender sender = new CoordinatesToServerSender();
Observable.interval(AppConstants.SEND_LOCATIONS_INTERVAL_IN_MINUTES, TimeUnit.MINUTES)
.observeOn(Schedulers.newThread())
.serialize()
.retry()
.subscribe(new Action1<Long>() {
public void call(Long _) {
sender.execute();
}
},
new Action1<Throwable>() {
public void call(Throwable error) {
mLog.error(error, "SEND_LOCATIONS_FAILED", );
}
});
编辑1:
我删除了.observeOn(Schedulers.newThread())
哪些是多余的Observable.interval
CoordinatesToServerSender sender = new CoordinatesToServerSender();
Observable.interval(AppConstants.SEND_LOCATIONS_INTERVAL_IN_MINUTES, TimeUnit.MINUTES)
.retry()
.serialize()
.subscribe(new Action1<Long>() {
public void call(Long _) {
sender.execute();
}
},
new Action1<Throwable>() {
public void call(Throwable error) {
mLog.error(error, "SEND_LOCATIONS_FAILED", );
}
});