https://kotlinlang.org logo
#compose
Title
# compose
c

Chethan

10/28/2020, 12:25 PM
Hello , why the UploadPhots doesn’t recompose with change in value _uploadItems , what I am missing and not understood ?
Copy code
@Composable
fun UploadPhotos(
    viewModel: YourViewModel,
    imageAdapterClickLister: ImageAdapterClickLister
) {

    val userSelectedMediaList = viewModel.listOfSelectedImages.collectAsState()



    if (userSelectedMediaList.value.isEmpty())
        DefaultPlaceHolder(
            onClickOfUpload = {
                imageAdapterClickLister.onUploadMoreButtonClick()
               
            }
        )
    else
        SetUserSelectedMedia()
}
Copy code
class YourViewModel @ViewModelInject constructor(
    private val repository: YourReviewRepository
) : ViewModel() {

    private val _uploadItems = MutableStateFlow(mutableListOf<UploadedItem>())
    val listOfSelectedImages: StateFlow<List<UploadedItem>> get() = _uploadItems

    fun addSelectedMediaToList(userSelectedUploadItem: UploadedItem) {

         val listWithNewlyAddedItem = _uploadItems.value.also {
            it.add(userSelectedUploadItem)
        }

        _uploadItems.value = listWithNewlyAddedItem
    }
}
z

Zach Klippenstein (he/him) [MOD]

10/28/2020, 2:20 PM
As a general rule, never send mutable objects through streams like Flows or Observables. 1. It makes code very difficult to reason about and prone to bugs - an observer with a reference to the list can have the list change out from under them at any time. 2. In this case, since it's the same instance of the list object, StateFlow thinks it's the same value and won't re-emit. The best fix here is to make the list immutable (use List instead of MutableList, emptyList () instead of mutableListOf()), and then create a new list when new items come in and send the new list through the flow. You can use the plus operator on immutable lists, eg
stateFlow.value += newItem
👍 1
c

Chethan

10/29/2020, 1:03 AM
Thanks lot, I didn’t know this fact, it worked for me after changing it as explained above , below is the modified code and it worked for me, now the recompose happens
Copy code
private val _uploadItems = MutableStateFlow(emptyList<UploadedItem>())
val listOfSelectedImages: StateFlow<List<UploadedItem>> get() = _uploadItems

fun addSelectedMediaToList(userSelectedUploadItem: UploadedItem) {


    val newList = mutableListOf<UploadedItem>().also {
        it.addAll(_uploadItems.value)
        it.add(userSelectedUploadItem)
    }
    _uploadItems.value = newList
}
2 Views