本篇使用RxAndroid开发从网络上下载图片的示例
MainActivity中有一个Button和一个ImageView,当点击Button的时候,从网络上下载一张图片展示到ImageView中
/**
* 返回一个被观察者
*/
public static Observable<byte[]> downloadPic(final String urlPath)
{
return Observable.create(new ObservableOnSubscribe<byte[]>()
{
@Override
public void subscribe(final ObservableEmitter<byte[]> observer) throws Exception
{
OkHttpClient mOkHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(urlPath)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(Call call, IOException ex)
{
observer.onError(ex);
}
@Override
public void onResponse(Call call, Response response) throws IOException
{
if (response.isSuccessful())
{
observer.onNext(response.body().bytes());
} else
{
observer.onNext(null);
}
observer.onComplete();
}
});
}
});
}
public void onClick(View v)
{
UtilDownload.downloadPic(urlPath).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new Observer<byte[]>()
{
@Override
public void onSubscribe(Disposable d)
{
System.out.println("onSubscribe");
}
@Override
public void onNext(byte[] value)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(value, 0, value.length);
imageView.setImageBitmap(bitmap);
}
@Override
public void onError(Throwable e)
{
System.out.println(e.getMessage());
}
@Override
public void onComplete()
{
}
});
}