Reputation: 2431
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;
I suppose it´s a threading issue (Garbage Collection of some sort) in that the AsyncTask is not runned nor instantiated. When i held a reference to the instantiated AsyncTask and only call .execute from the subscription it works.
I know the logical thing to do is not to use AsyncTask in the Subscription. I was in a process o migrating from recurrent AsyncTasks. I later refactored sending logic into a non-AsyncTask class and all´s good.
I´m just curious to why this didn´t work in the first place. Is it because the Timer ended before Async task was ran? i.e OnNext ended before the task, there by ending the timer thread on OnComplete?
But what i really wanted and finally did was this:
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", );
}
});
EDIT 1:
I removed the .observeOn(Schedulers.newThread())
which is redundant for 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", );
}
});
Upvotes: 2
Views: 505
Reputation: 2883
As you said, mixing AsyncTasks and RxJava is far from ideal, since you have a very powerful composition mechanism available to you on RxJava, and you can actually execute the work of your async task, by composing it to your Observable (and using an scheduler to get it of the main thread).
But to try and help with this issue, have you tried doing observeOn(AndroidSchedulers.mainThread())
? Async threads are supposed to be launched on the main thread, so that may be your problem
Upvotes: 1