Skip to content

Instantly share code, notes, and snippets.

@attilakruchio
Created June 26, 2022 17:36
Show Gist options
  • Save attilakruchio/f8e4382845b417c3063e2cb8b05e0e2c to your computer and use it in GitHub Desktop.
Save attilakruchio/f8e4382845b417c3063e2cb8b05e0e2c to your computer and use it in GitHub Desktop.
Gist for 'Assigning value to a StateFlow with '.value = .value.copy()' introduces a race condition. Do this now!' Medium article
class HomeViewModel : ViewModel() {
private val _state = MutableStateFlow(State())
val state = _state.asStateFlow()
init {
loadContacts()
loadDeliveryList()
}
private fun loadContacts() {
viewModelScope.launch {
val contactList = FakeContactApi.loadContacts()
_state.update { previousState ->
previousState.copy(
contactList = contactList
)
}
}
}
private fun loadDeliveryList() {
viewModelScope.launch {
val deliveryList = FakeDeliveryApi.loadDeliveryList()
_state.update { previousState ->
previousState.copy(
deliveryList = deliveryList
)
}
}
}
data class State(
val contactList: List<String> = emptyList(),
val deliveryList: List<String> = emptyList(),
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment