0

I'm working on an Android app in Jetpack Compose using a model-viewmodel-view architecture. I'm not seeing my views refreshed after I update the state variables in the app.

I have a variable defined as follows in my view. This var is passed to other Composables which draw the screen. Changes to it are not being picked up.

val crusadeCardUiState = viewModel.crusadeCardUiState.collectAsState()

In my view model, I have the following definitions which define a class and update it in my Room db.

The class definition

@Entity(tableName = "crusadecard", primaryKeys = ["includedUnitId"])
data class CrusadeCard(
    var includedUnitId: Int,
    var crusadePoints: Int,
    var battles: Int,
    var victories: Int,
    var xp: Int,
    var rank: String,
    var unitsDestroyed: Int,
    var battleScars: String,
    var battleTraits: String,
    var crusadeRelics: String,
    var weaponModifications: String
)

private suspend fun updateCrusadeCard() {
      unitRepository.updateCrusadecard(crusadeCardUiState.value.crusadeCardDetails.toCrusadeCard())     
}

val crusadeCardUiState: StateFlow<CrusadeCardUiState> =
        unitRepository.getCrusadeCardForIncludedUnitStream(includedUnitId)
            .filterNotNull()
            .map {
                CrusadeCardUiState(
                    crusadeCardDetails = it.toCrusadeCardDetails()
                )
            }.stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(TIMEOUT_MILLIS),
                initialValue = CrusadeCardUiState()
            )

When I update crusadeCardUiState.value.crusadeCardDetails.crusadePoints by calling updateCrusadeCard the value is updated correctly in the database but the view is not refreshed.

If I update the value manually through Database Inspector the view is updated.

What do I need to do to get the view to refresh when the value is updated through code?

1 Answer 1

0

I fixed this by changing the data class definition so that the properties are all val rather than var.

And also changing this from a val to a var (missed from the original post)

data class CrusadeCardUiState(
    val crusadeCardDetails: CrusadeCardDetails = CrusadeCardDetails()
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.