本教程內(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).
如果你請求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ù)制給其他變量了。