Home > OS >  I get the same Download URL for all users inside an items in LaxyRow Jetpack Compose
I get the same Download URL for all users inside an items in LaxyRow Jetpack Compose

Time:08-21

I have a list of users. Each user has a profile picture in storage that has a URL like this:

gs://my-app.appspot.com/users/uid.png

This list is displayed in a LazyRow:

LazyRow(
    modifier = Modifier.fillMaxWidth()
) {
    items(users) { user ->
        LaunchedEffect(user.id) {
            viewModel.getDownloadUrl(user.uid)
        }
        when(val response = viewModel.response) {
            is Result.Loading -> Unit
            is Result.Success -> {
                user.downloadUrl = response.data
                UserCard(
                    user = user
                )
            }
            is Result.Failure -> print(response.e)
        }
    }
}

Since common libraries doesn't know how to read that reference, I need to convert to a real URL. So at each iteration, I create a call to get the download URL. The problem is that I get the same picture for all users and if scroll right, I get other pictures, but doubled, tripled. I don't understand why. How to overcome this situation?

CodePudding user response:

Fetching download URLs is domain logic. So it should be handled in ViewModel, Repository, or Data Source wherever appropriate according to the project.

For example, if we decide to handle it in ViewModel.

We would be fetching the list of Users from the repository in the ViewModel. Once we have the list, we can create a new Model class that has all the data from the User model class required in the UI layer along with the download URL.

Then we can emit that list from ViewModel and collect it in the UI as use as required.

Alternatively, we can also create a new list of download URLs and emit both the list of users fetched from the repository and the list of download URLs created in the ViewModel.

In the ViewModel, we can collect both lists to use as required.

The download URL of the nth user will be the nth item in the list.

  • Related