Created
June 26, 2022 17:36
-
-
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
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.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