How to implement MVVM pattern

AndroidX provides classes to implement the MVVM pattern.

Dependencies:

The ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity/Fragment with the rest of the application.

LiveData is an observable data holder class. Unlike a regular observable, it takes into account the lifecycle of other app components, such as activities, fragments, or services.

A LiveData object is usually stored within a ViewModel object.

class NameViewModel : ViewModel() {

    // Create a LiveData with a String
    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    // ...
}

In most cases, an app component’s onCreate() method is the right place to begin observing a LiveData object.

class NameActivity : AppCompatActivity() {

    // Use the 'by viewModels()' Kotlin property delegate
    // from the activity-ktx artifact
    private val model: NameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // ...
        
        // Create the observer which updates the UI.
        val nameObserver = Observer<String> { newName ->
            // Update the UI, in this case, a TextView.
            nameTextView.text = newName
        }

        // Observe the LiveData, passing in this activity 
        // as the LifecycleOwner and the observer.
        model.currentName.observe(this, nameObserver)
    }
}
public class NameActivity extends AppCompatActivity {

    private NameViewModel model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // ... 
        
        // Get the ViewModel
        model = new ViewModelProvider(this).get(NameViewModel.class);

        // Create the observer which updates the UI.
        final Observer<String> nameObserver = new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String newName) {
                nameTextView.setText(newName); // update the UI, in this case, a TextView.
            }
        };

        // Observe the LiveData, passing in this activity 
        // as the LifecycleOwner and the observer.
        model.getCurrentName().observe(this, nameObserver);
    }
}