Skip to content

Instantly share code, notes, and snippets.

@iSanechek
Created March 10, 2020 21:36
Show Gist options
  • Select an option

  • Save iSanechek/ed6822673c308195e3fa42ecdeeaac84 to your computer and use it in GitHub Desktop.

Select an option

Save iSanechek/ed6822673c308195e3fa42ecdeeaac84 to your computer and use it in GitHub Desktop.
@Composable
fun image(data: Any):Image? {
// Positionally memoize the request creation so
// it will only be recreated if data changes.
val request = remember(data) {
Coil.loader().newGetBuilder().data(data).build()
}
return image(request)
}
/**
* A configurable [image] effect, which accepts a [request] value object.
*/
@Composable
fun image(request: GetRequest) : Image? {
val image = stateFor<Image?> { null }
// Execute the following code whenever the request changes.
onCommit(request) {
val job = CoroutineScope(Dispatchers.Main.immediate).launch {
// Start loading the image and await the result.
val drawable = Coil.loader().get(request)
image.value = AndroidImage(drawable.toBitmap())
}
// Cancel the request if the input to onCommit changes or
// the Composition is removed from the composition tree.
onDispose { job.cancel() }
}
// Emit a null Image to start with.
return image.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment