Skip to content

Instantly share code, notes, and snippets.

@LanderlYoung
Last active September 24, 2021 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanderlYoung/08639dcd5238f99ba2e8bfa177515b01 to your computer and use it in GitHub Desktop.
Save LanderlYoung/08639dcd5238f99ba2e8bfa177515b01 to your computer and use it in GitHub Desktop.
MVVM compare
class ViewModel_1 {
val name = LiveData<String>()
val gender = LiveData<Boolean>()
val loading = LiveData<Boolean>()
val errorMessage = LiveEvent<String>()
fun follow() {
api.follow(xxx)
}
}
fun UI_1(vm: ViewModel_1) {
nameTextView.bind(vm.name)
nameTextView.bindTextColor(vm.gender, map = {
if (it) Color.RED else Color.BLUE
})
loadingView.bindVisibility(vm.loading)
vm.errorMessage.observer { Toast.show(it) }
followButton.onClick { vm.follow() }
}
// =============================================================
class ViewModel_2 {
val name = LiveData<String>()
val gender = LiveData<Boolean>()
fun follow(
onSuccess: () -> Unit,
onFail: () -> Unit
): Boolean {
api.follow(xxx)
}
}
fun UI_2(vm: ViewModel_2) {
nameTextView.bind(vm.name)
nameTextView.bindTextColor(vm.gender, map = {
if (it) Color.RED else Color.BLUE
})
followButton.onClick {
loadingView.show()
val success = vm.follow(
onSuccess = {
loadingView.hide()
},
onFail = {
loadingView.hide()
Toast.show(it.errorMessage)
}
)
if (!success) {
loadingView.hide()
Toast.show("no network")
}
}
}
// =============================================================
sealed class UserInfoIntent {
class Login : UserInfoIntent()
class Follow : UserInfoIntent()
}
class UserInfoVM : ViewModel<UserInfoIntent>() {
val name = LiveData<String>()
val gender = LiveData<Boolean>()
val loading = LiveData<Boolean>()
val errorMessage = LiveEvent<String>()
override fun handleIntent(intent: UserInfoIntent) {
when (intent) {
is UserInfoIntent.Follow -> follow()
// is UserInfoIntent.Login -> login()
}
}
private fun follow() {}
}
fun UI_3(vm: UserInfoVM) {
nameTextView.bind(vm.name)
nameTextView.bindTextColor(vm.gender, map = {
if (it) Color.RED else Color.BLUE
})
loadingView.bindVisibility(vm.loading)
vm.errorMessage.observer { Toast.show(it) }
followButton.onClick { vm.handleIntent(UserInfoIntent.Follow) }
}
// the vm
abstract class ViewModel<T : Any> {
abstract fun handleIntent(intent: T)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment