我是RxJava的新手。我有一个bitmapObservable
,用于下载图像URL列表并将其转换为位图的简单网络操作。
mSubscription = Observable.create(new Observable.OnSubscribe<Bitmap[]>() {
@Override
public void call(final Subscriber<? super Bitmap[]> subscriber) {
String[] urls = new String[]{
"http://www.convertimage.net/frontframe/images/cute_ball_info.png",
"http://customerserviceai.com/wp-content/uploads/2016/08/waiting.png",
"https://images.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png"};
Bitmap[] bitmaps = new Bitmap[urls.length];
int i = 0;
for (String url : urls) {
final Bitmap bitmap = Downloader.getBitmapFromURL(url);
if (bitmap == null) {
subscriber.onError(new IOException());
} else {
bitmaps[i++] = bitmap;
Log.d(TAG, "Bitmap " + url + " downloaded" + bitmap);
}
}
subscriber.onNext(bitmaps);
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Bitmap[]>() {
@Override
public void onCompleted() {
Log.d(TAG, "Everything completed");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "Some error has been occured");
}
@Override
public void onNext(Bitmap[] bitmaps) {
Log.d(TAG, "Downloaded bitmaps " + bitmaps);
}
});
在Activity的
onDestroy
方法中,我会取消订阅Observable,以避免内存泄漏。 @Override
protected void onDestroy() {
mSubscription.unsubscribe();
super.onDestroy();
}
我所看到的是,在图片下载过程中,如果我离开了活动界面,后台任务也会被杀死。我只想要继续后台任务,即使我已经取消订阅观察者。这可能吗?