mardi 3 août 2021

Please review my simple viewmodel code in Android MVVM architecture

This is My ViewModel Code.

private val _name: MutableLiveData<String> by lazy {
        MutableLiveData<String>("")
    }
    val name: LiveData<String>
    get() = _name

    private val _birthday: MutableLiveData<String> by lazy {
        MutableLiveData<String>("")
    }
    val birthday: LiveData<String>
    get() = _birthday

    private val _email: MutableLiveData<String> by lazy {
        MutableLiveData<String>("")
    }
    val email: LiveData<String>
    get() = email

    private val _isClickable: MutableLiveData<Boolean> by lazy {
        MutableLiveData<Boolean>(false)
    }
    val isClickable: LiveData<Boolean>
    get() = _isClickable

    fun update(
            userName: String? = null,
            userBirthday: String? = null,
            userEmail: String? = null
    ) {
        userName?.let { _name.value = userName }
        userBirthday?.let { _birthday.value = userBirthday }
        userEmail?.let { _email.value = userEmail }
        val canSubmit = (_name.value?.isNotBlank() ?: false)
                && (_birthday.value?.isNotBlank() ?: false)
                && (_email.value?.isNotBlank() ?: false)
        _isClickable.value?.let {
            if (it!=canSubmit) {
                _isClickable.value = canSubmit
            }
        }
    }

and my activity code is below. Activity

I'm not sure properly using viewmodel... It looks a bit messy, There seems to be room for improvement.

Anything should be changed? plz any review for my code guys...! :) thanks!

Aucun commentaire:

Enregistrer un commentaire