1. 程式人生 > >使用RxJava和Glide儲存圖片

使用RxJava和Glide儲存圖片

 RxJava的基本框架

Observable.create(new ObservableOnSubscribe<Boolean>() {
    @Override
    public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
       //TODO 處理下載圖片的操作
    }
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
    @Override
    public void accept(Boolean result) throws Exception {
        //TODO 處理結果
    }
});
ObserveOn和SubscribeOn這兩個是用來做執行緒的切換

Glide  本身提供了一個簡潔的方法  downloadOnly  提供下載 ,返回一個FutureTarget介面來處理結果

具體圖片處理程式碼:

 FutureTarget<File> futureTarget = Glide.with(EditDataImageActivity.this).load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

File fileImg = futureTarget.get(); 

不過這裡有個問題,下載不到圖片資源的時候,比如說404,這裡就需要處理一下異常否則會報錯

 

全部程式碼:

 private void saveImg(final String imgUrl) {
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                FutureTarget<File> futureTarget = Glide.with(EditDataImageActivity.this).load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                try{
                    File fileImg = futureTarget.get();
                    String imgDirUrl = SDCardUtils.getSDCardPath() + File.separator + YlMApplication.getInstance().getPackageName() + File.separator + "images";
                    File imgDir = new File(imgDirUrl);
                    if (!imgDir.exists()) {
                        imgDir.mkdirs();
                    }
                    String imgName = System.currentTimeMillis() + imgUrl.substring(imgUrl.lastIndexOf("."), imgUrl.length());
                    File destFile = new File(imgDir, imgName);
                    //複製圖片到自己自定義的位置
                    boolean result = FileUtils.copyFile(fileImg, destFile);
                    e.onNext(result);
                }catch (Exception e1){
                    e.onNext(false);
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean result) throws Exception {
                if (result) {
                    ToastUtils.show("圖片儲存成功!");
                } else {
                    ToastUtils.show("圖片儲存失敗!");
                }
            }
        });
    }