androidmvvmkotlinandroid-databinding

MVVM+Kotlin+Databinding best practice


I am building an app on MVVM+Kotlin+Databinding, and i have this situation i am stuck at. I have LoginFragment which has a phone number edittext and a button, Now i need to check if the phone number is empty or not when user clicks the button. Normally i would do that by using this code in my fragment.

if(!binding!!.phone.text.isEmpty()) {
    //do something
}

But according to experts my view should not know anything about the business logic, Hence i need to have this check inside my viewModel. so what should be the best way to achieve this?


Solution

  • Here is the bet practice to achieve that (from my point of view):

    In your layout add text watcher and text to your EditText

    android:text="@{view_model.phone}"
    app:addTextChangedListener="@{view_model.phoneWatcher}"
    

    and on click method to your button

    android:onClick="@{() -> view_model.save()}"
    

    Inside the ViewModel you will have text observable and a watcher

    val phone = ObservableField<String?>()
    
    val phoneWatcher = object : TextWatcherAdapter() {
        override fun afterTextChanged(s: Editable?) {
            phone.set(s?.toString())
        }
    }
    

    Now you can make your check inside ViewModel

    fun save() {
        if (phone.get()?.isNotEmpty == true) {
            // TODO: do something
        }
    }
    

    Also please note that it is a best practice to avoid doing something like that binding!!.phone in Kotlin. If you're using !! to make a possible nullable object look like it is not-nullable (even if you're 100% sure it is) - you're doing something wrong.