问题描述
我需要通过给定的URL下载图片(位图).当我在项目中使用Glide来显示图片时,我以为我也可以简单地使用它们的机制来下载图片.我需要在RxJava环境中使用它,我的问题是没有调用回调onResourceReady(),当然也没有调用subscriber.onNext()和subscriber.onCompleted()方法.
I need to download pictures (Bitmaps) via a given url. As I use Glide in my project to display the pictures I thought I could simply use their mechanism to download the pictures as well. I need to use it in a RxJava Environment and my problem is that the callback onResourceReady() is not called and of course the methods subscriber.onNext() and subscriber.onCompleted() are not getting called either.
我得到一个IllegalStateException(见下文).我猜对Glide的调用需要在主线程上完成,而不是在将要调用get()的io线程上进行.有没有办法做到这一点?
I get an IllegalStateException (see below). I guess the call to Glide needs to be done on the main thread instead of the io thread where get() will be called. Is there a way to achieve this?
这是id的作用:
public Observable<Bitmap> get(final String url) {
return Observable.create(new Observable.OnSubscribe<Bitmap>() {
@Override
public void call(final Subscriber<? super Bitmap> subscriber) {
Glide
.with(context)
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
// the method onResourceReady is not getting called
subscriber.onNext(resource);
subscriber.onCompleted();
}
});
}
});
}
推荐答案
我已如下修复.不幸的是,我没有找回位图,但这对我来说现在还可以.
I fixed it like below. Unfortunately I do not get the bitmap back but that is ok-ish for me for the moment.
public Completable get(final String url) {
return Completable.create(new CompletableOnSubscribe() {
@Override
public void subscribe(CompletableEmitter emitter) throws Exception {
Glide
.with(context)
.load(url)
.downloadOnly(2000, 2000);
emitter.onComplete();
}
});
}
这篇关于使用rxJava通过Glide下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!