Skip to content

Instantly share code, notes, and snippets.

@attilakruchio
Created June 26, 2022 19:07
Show Gist options
  • Save attilakruchio/2b08d38e8d9472dc144e6cbef1f85191 to your computer and use it in GitHub Desktop.
Save attilakruchio/2b08d38e8d9472dc144e6cbef1f85191 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 _contacts = MutableStateFlow<List<String>>(emptyList())
private val _deliveryList = MutableStateFlow<List<String>>(emptyList())
val state = combine(_contacts, _deliveryList) { contacts, deliveryList ->
State(
contactList = contacts,
deliveryList = deliveryList,
)
}.distinctUntilChanged()
init {
loadContacts()
loadDeliveryList()
}
private fun loadContacts() {
viewModelScope.launch {
_contacts.value = FakeContactApi.loadContacts()
}
}
private fun loadDeliveryList() {
viewModelScope.launch {
_deliveryList.value = FakeDeliveryApi.loadDeliveryList()
}
}
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