Skip to content

Instantly share code, notes, and snippets.

@thearchetypee
Created April 23, 2023 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thearchetypee/0fddc453b3b33314436b1659b0ed28da to your computer and use it in GitHub Desktop.
Save thearchetypee/0fddc453b3b33314436b1659b0ed28da to your computer and use it in GitHub Desktop.
@Composable
fun loadNetworkImage(
url: String,
imageRepository: ImageRepository = ImageRepository()
): State<Result<Image>> {
// Creates a State<T> with Result.Loading as initial value
// If either `url` or `imageRepository` changes, the running producer
// will cancel and will be re-launched with the new inputs.
return produceState<Result<Image>>(initialValue = Result.Loading, url, imageRepository) {
// In a coroutine, can make suspend calls
val image = imageRepository.load(url)
// Update State with either an Error or Success result.
// This will trigger a recomposition where this State is read
value = if (image == null) {
Result.Error
} else {
Result.Success(image)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment