I\'m trying to replace Picasso in my android app with Fresco. However I am unsure of how to simply load a bitmap using Fresco.
With Picasso I would just do the foll
Starting from this answer I created a quick implementation that uses Kotlin extensions and RxJava to get a ClosableBitmap from an ImageRequest:
fun ImageRequest.getBitmap(context: Context): Maybe> {
val dataSource = Fresco.getImagePipeline().fetchDecodedImage(this, context)
return Maybe.create { emitter ->
dataSource.subscribe(
object : BaseDataSubscriber>() {
override fun onFailureImpl(dataSource: DataSource>) {
emitter.onComplete()
}
override fun onNewResultImpl(dataSource: DataSource>) {
if (!dataSource.isFinished) {
return
}
dataSource.result
?.takeIf { it.get() is CloseableBitmap }
?.let {
@Suppress("UNCHECKED_CAST")
emitter.onSuccess(it as CloseableReference)
}
emitter.onComplete()
}
},
DefaultExecutorSupplier(1).forBackgroundTasks()
)
}
}
Since by contract it is required to close the reference once the bitmap has been used, I created this util function:
/**
* The bitmap passed into [block] is only valid during the execution of the method.
*/
fun CloseableReference.useBitmap(block: (Bitmap?) -> T): T? {
return try {
this.get()?.underlyingBitmap?.let { block(it) }
} finally {
CloseableReference.closeSafely(this)
}
}