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.
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
}
Use SnapshotStateMap instead of HashMap:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With