Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my composable not recomposing on changing value for MutableState of HashMap?

Why my composable not recomposing on changing value for MutableState of HashMap.

ViewModel

 val imageList: MutableState<HashMap<Int, Uri>> = mutableStateOf(HashMap())
    fun setImage(imageUri: Uri) {
        imageList.value[imagePosition] = imageUri
    }

Fragment

if (viewModel.imageList.value[stepNo] != null && !TextUtils.isEmpty(
                                            viewModel.imageList.value[stepNo].toString()
                                        )
                                    ) {
                                        Image(
                                            contentDescription = "Recipe",
                                            painter = painterResource(R.drawable.ic_baseline_fastfood_24),
                                            modifier = Modifier
                                                .padding(8.dp)
                                        )
                                    }

fun permissionCallbacks() {
        imagePickerListener =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    // There are no request codes
                    val data: Intent? = result.data
                    val selectedImageUri = data?.data
                    selectedImageUri?.let { viewModel.setImage(it) }
                }
            }
        requestPermissionLauncher =
            registerForActivityResult(
                ActivityResultContracts.RequestPermission()
            ) { isGranted: Boolean ->
                if (isGranted) {
                    val galleryIntent = Intent(
                        Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                    )
                    galleryIntent.type = "image/*"
                    imagePickerListener?.launch(galleryIntent)
                } else {
                   
                }
            }
    }

I see by debugging that value correctly set inside setImage() method but if condition for viewModel.imageList.value[stepNo] is not called again when value for hashmap is changed.

like image 886
Android Developer Avatar asked Feb 04 '26 06:02

Android Developer


2 Answers

mutableStateOf can only track when you replace one value with an other one. If you change state of current value no way it can handle it

You can use mutableStateMapOf instead of mutableStateOf(HashMap()):

val imageList = mutableStateMapOf<Int, Uri>()
---
fun setImage(imageUri: Uri) {
    imageList[imagePosition] = imageUri
}
like image 196
Philip Dukhov Avatar answered Feb 05 '26 21:02

Philip Dukhov


Use SnapshotStateMap instead of HashMap:

enter image description here

like image 34
Senocico Stelian Avatar answered Feb 05 '26 19:02

Senocico Stelian