Skip to content

Instantly share code, notes, and snippets.

@jishindev
Created July 2, 2019 06:30
Show Gist options
  • Save jishindev/34d8e8117e42c157ddf5cbccb86ae079 to your computer and use it in GitHub Desktop.
Save jishindev/34d8e8117e42c157ddf5cbccb86ae079 to your computer and use it in GitHub Desktop.
Data fetcher that can be registered with a Glide module to load data from AWS S3 Storage
class AwsDataFetcher(private val s3Client: AmazonS3Client, private val awsImage: AwsImage) : DataFetcher<InputStream> {
override fun getDataClass() = InputStream::class.java
override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in InputStream>) {
callback.onDataReady(
s3Client.getObject(
GetObjectRequest(
awsImage.bucket,
awsImage.imageKey
)
).objectContent
)
}
override fun getDataSource() = DataSource.REMOTE
override fun cleanup() {}
override fun cancel() {}
}
class AwsImageLoader(private val s3Client: AmazonS3Client) : ModelLoader<AwsImage, InputStream> {
override fun buildLoadData(
model: AwsImage,
width: Int,
height: Int,
options: Options
): ModelLoader.LoadData<InputStream>? {
return ModelLoader.LoadData(ObjectKey(model), AwsDataFetcher(s3Client, model))
}
override fun handles(model: AwsImage): Boolean {
return !model.imageKey.isNullOrEmpty()
}
}
class AwsImageLoaderFactory(private val s3Client: AmazonS3Client) : ModelLoaderFactory<AwsImage, InputStream> {
override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<AwsImage, InputStream> {
return AwsImageLoader(s3Client)
}
override fun teardown() {}
}
data class AwsImage(val imageKey: String?, val bucket: String = AWS_S3_BUCKET)
/* AWS images */
fun ImageView.loadAwsImage(
awsImage: AwsImage?,
thumbnailFactor: Float = SCALE_FACTOR_FULL_SIZE,
shape: RequestOptions? = null
) =
Glide.with(context)
.load(awsImage).apply { shape?.let { apply(it) } }
.thumbnail(thumbnailFactor)
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment