Last active
September 24, 2021 02:23
-
-
Save LanderlYoung/08639dcd5238f99ba2e8bfa177515b01 to your computer and use it in GitHub Desktop.
MVVM compare
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 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