Home > Software design >  How to set am image using AsyncImage when getting data from Firebase?
How to set am image using AsyncImage when getting data from Firebase?

Time:05-26

I have a repository class, where I create a Firestore call to get an image URL:

override suspend fun getImageUrl() = flow {
    try {
        emit(Response.Loading)
        val imageUrl = ref.document(id).get().await().getString("imageUrl")
        emit(Response.Success(imageUrl))
    } catch (e: Exception) {
        emit(Response.Failure(e))
    }
}

In the ViewModel class I have a State object where I set the URL like this:

var imageUrlState = mutableStateOf<Response<String>>(Response.Success(null))

init {
    getImageUrl()
}

fun getImageUrl() {
    viewModelScope.launch {
        repo.getImageUrl().collect { response ->
            imageUrlState.value = response
        }
    }
}

Inside my ProfileScreen I have this:

@Composable
fun ProfileScreen(
    viewModel: ImageUrlViewModel = hiltViewModel()
) {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        AsyncImage(
            model = ImageRequest.Builder(LocalContext.current)
                .data(viewModel.imageUrlState.value) //           
  • Related