Asynchronous loading of Drawable Functions for the Glide library
Lazy and asynchronous loading of Drawables
with the Glide library.
Base Library:
implementation 'com.github.chRyNaN.glide-drawable:library:VERSION'
Drawable Function Implementations:
implementation 'com.github.chRyNaN.glide-drawable:feature:VERSION'
Pass in a function that returns a Drawable
instance into Glide. The function will be resolved asynchronously and the Drawable
will be cached using Glide.
Glide.with(context)
.loadFunction { getMyDrawable() }
.into(imageView)
// Or
Glide.with(context)
.load(myDrawableFunctionClassImplementation)
.into(imageView)
Register the DrawableFunction
class:
@GlideModule
class SearchAppGlideModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.prepend(DrawableFunction::class.java, Drawable::class.java, DrawableFunctionLoaderFactory())
}
}
This approach is different from using the load(getMyDrawable())
function because that would resolve the drawable synchronously when the function is called. Passing a function to load, load(f: () -> Drawable)
, resolves the Drawable
asynchronously.
DrawableFunction
Create the implementation class:
class ApplicationIconDrawableFunction(
private val packageManager: PackageManager,
private val packageName: String
) : DrawableFunction {
companion object {
private const val PACKAGE_ID_PREFIX = "application
"
}
override val uniqueKey: Key
get() = ObjectKey("$PACKAGE_ID_PREFIX$packageName")
override val function: () -> Drawable
get() = { packageManager.getApplicationIcon(packageName) }
}
Register the class:
@GlideModule
class SearchAppGlideModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.prepend(ApplicationIconDrawableFunction::class.java, Drawable::class.java, DrawableFunctionLoaderFactory())
}
}
Some common implementations of DrawableFunction
are provided through the feature
library. This library is optional but is useful if those implementations are needed.
The ApplicationIconDrawableFunction
shown above, is provided in the feature
library.