Created
June 26, 2022 19:07
-
-
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
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 _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