Created
June 26, 2022 16:47
-
-
Save attilakruchio/b571420c683f8002985005987b53785a 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.value = _state.value.copy( | |
contactList = contactList | |
) | |
} | |
} | |
private fun loadDeliveryList() { | |
viewModelScope.launch { | |
val deliveryList = FakeDeliveryApi.loadDeliveryList() | |
_state.value = _state.value.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