admin管理员组

文章数量:1122846

I have a shared viewModel in which I am trying to update a MutableStateFlow list. I get the new item to save, but after adding it to that particular list, I don't find it in the list... addOrUpdateTempTransport is called from my view.

private val _tempTransportDetails = MutableStateFlow<List<TransportView>>(listOf())
val tempTransportDetails: StateFlow<List<TransportView>> = _tempTransportDetails

val allTransportDetails = combine(
    _transportDetails,
    _tempTransportDetails
) { savedTransports, tempTransports ->
    Log.d("StayDetailsViewModel", "Saved Transports = $savedTransports")
    Log.d("StayDetailsViewModel", "Temp Transports = $tempTransports")

    val combined = savedTransports + tempTransports
    Log.d("StayDetailsViewModel", "Combined without filter: $combined")

    Log.d("StayDetailsViewModel", "Combined Transports: $combined")
    combined
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

fun addOrUpdateTempTransport(transport: TransportView) {
    Log.d("StayDetailsViewModel", "Temp Transport before update: ${_tempTransportDetails.value}")

    val updatedList = _tempTransportDetails.value.toMutableList().apply {
        val index = indexOfFirst { it.id == transport.id }
        if (index != -1) {
            this[index] = transport // Mettre à jour l'élément existant
        } else {
            add(transport) // Ajouter un nouveau transport
        }
    }
    _tempTransportDetails.value = updatedList
    Log.d("StayDetailsViewModel", "After update: ${_tempTransportDetails.value}")
}

Here the logs to help you to understand my non mother language :) Thank you all. Logs

EDIT

I tried with a new list, same result

fun addOrUpdateTempTransport(transport: TransportView) {
    // Créer une nouvelle liste distincte à partir des éléments de _tempTransportDetails
    val updatedList = mutableListOf<TransportView>().apply {
        // Parcourir chaque élément de _tempTransportDetails et l'ajouter à la nouvelle liste
        _tempTransportDetails.value.forEach { item ->
            add(item)
        }
        // Ajouter le nouvel objet transport
        add(transport)
    }

    // Mettre à jour _tempTransportDetails avec cette nouvelle liste
    _tempTransportDetails.value = updatedList

    // Log pour déboguer
    Log.d("StayDetailsViewModel", "Updated tempTransportDetails with new list: ${_tempTransportDetails.value}")
}

本文标签: androidUpdate of MutableStateFlow List doesn39t work in KotlinStack Overflow