鍍金池/ 教程/ Android/ 數(shù)據(jù)源和數(shù)據(jù)訂閱者
進(jìn)度條
在JAVA代碼中使用Drawees
Drawee的各種效果配置
緩存
一些陷阱
關(guān)于在Android Studio中編譯
多圖請求及圖片復(fù)用
自定義網(wǎng)絡(luò)加載
支持的URIs
可關(guān)閉的引用
監(jiān)聽下載事件
修改圖片
引入Fresco
縮放
圓角和圓圈
配置Image Pipeline
縮放和旋轉(zhuǎn)圖片
(圖片請求)Image Requests
自定義View
使用ControllerBuilder
在XML中使用Drawees
開始使用 Fresco
關(guān)鍵概念
Image Pipeline介紹
漸進(jìn)式JPEG圖
數(shù)據(jù)源和數(shù)據(jù)訂閱者
直接使用Image Pipeline
動畫圖(gif)
使用其他的Image Loader

數(shù)據(jù)源和數(shù)據(jù)訂閱者

本教程內(nèi)容來源于:http://fresco-cn.org
采用 知識共享 署名 4.0 國際 許可協(xié)議 進(jìn)行許可

數(shù)據(jù)源Future, 有些相似,都是異步計算的結(jié)果。

不同點(diǎn)在于,數(shù)據(jù)源對于一個調(diào)用會返回一系列結(jié)果,F(xiàn)uture只返回一個。

提交一個Image request之后,Image pipeline返回一個數(shù)據(jù)源。從中獲取數(shù)據(jù)需要使用數(shù)據(jù)訂閱者(DataSubscriber).

當(dāng)你僅僅需要Bitmap

如果你請求Image pipeline僅僅是為了獲取一個 Bitmap, 對象。你可以利用簡單易用的BaseBitmapDataSubscriber:

dataSource.subscribe(new BaseBitmapDataSubscriber() {
    @Override
    public void onNewResultImpl(@Nullable Bitmap bitmap) {
       // You can use the bitmap in only limited ways
      // No need to do any cleanup.
    }

    @Override
    public void onFailureImpl(DataSource dataSource) {
      // No cleanup required here.
    }
  });

看起來很簡單,對吧。下面是一些小警告:

千萬 不要 把bitmap復(fù)制給onNewResultImpl函數(shù)范圍之外的任何變量。訂閱者執(zhí)行完操作之后,image pipeline 會回收這個bitmap,釋放內(nèi)存。在這個函數(shù)范圍內(nèi)再次使用這個Bitmap對象進(jìn)行繪制將會導(dǎo)致IllegalStateException。

通用的解決方案

如果你就是想維持對這個Bitmap對象的引用,你不能維持純Bitmap對象的引用,可以利用可關(guān)閉的引用(closeable references)BaseDataSubscriber:

DataSubscriber dataSubscriber =
    new BaseDataSubscriber<CloseableReference<CloseableImage>>() {
  @Override
  public void onNewResultImpl(
      DataSource<CloseableReference<CloseableImage>> dataSource) {

    if (!dataSource.isFinished()) {
      FLog.v("Not yet finished - this is just another progressive scan.");
    }  

    CloseableReference<CloseableImage> imageReference = dataSource.getResult();
    if (imageReference != null) {
      try {
        CloseableImage image = imageReference.get();
        // do something with the image
      } finally {
        imageReference.close();
      }
    }
  }
  @Override
  public void onFailureImpl(DataSource dataSource) {
    Throwable throwable = dataSource.getFailureCause();
    // handle failure
  }
};

dataSource.subscribe(dataSubscriber, executor);

這樣,只要遵守可關(guān)閉的引用使用規(guī)則,你就可以把這個CloseableReference復(fù)制給其他變量了。