Skip to content

Instantly share code, notes, and snippets.

@AradiPatrik
Created December 29, 2020 16:41
Show Gist options
  • Save AradiPatrik/baaf12b9785defbd8c85cf83346ac126 to your computer and use it in GitHub Desktop.
Save AradiPatrik/baaf12b9785defbd8c85cf83346ac126 to your computer and use it in GitHub Desktop.
MVI vs MVVM
// Here counter can show 1 after incrementCounter is called
class ExampleViewModel : ViewModel() {
private val _counter = MutableLiveData(0)
init {
viewModelScope.launch(Dispatchers.IO) {
// Thread 1
delay(500)
_counter.postValue(_counter.value?.plus(1))
}
}
fun incrementCounter() = viewModelScope.launch(Dispatchers.IO) { // UI calls this
// Thread 2
_counter.postValue(_counter.value?.plus(1))
}
// Thread 1 reads 0
// Thread 1 looses cpu
// Thread 2 reads 0
// Thread 2 looses cpu
// Thread 1 writes 1
// Thread 2 writes 1
}
// Here counter will always show 2 after incrementCounter called
class ExampleMviViewModel : ViewModel() {
init {
reduceState { state ->
delay(500)
state.copy(count = state.count + 1)
}
}
fun incrementCounter = reduceState { state ->
state.copy(count = state.count + 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment