hehe

Run ViewModel tests while using the init method

Adding tests into an application is something really necessary, specially if your application is being developed by a group of people. Not only because it ensures, somehow, that breaking changes are not put into the application, but because you can test changes or detect if something breaks in an easy way.

In Android, testing ViewModels is something rather necessary, because it ensures that your UI models get the expected information.

The init method

In Kotlin, you can do this with any class:

class HomeViewModel : ViewModel() {

    init {
        // Any code initialized when calling the constructor.
    }
}

The init is a initializer block, and basically, it executes anything you want to get when you call the constructor of the class (see Classes - Constructors). The equivalent in Java would be:

public class HomeViewModel extends ViewModel {

	public HomeViewModel() {
        // Any code initialized when calling the constructor.
	}
}

This behavior is common in applications where, for example, you need the data as soon as possible, and this is when you navigate into a View with a ViewModel and start loading the information while the rest of the View waits to get the needed information to display.

Example of using the init method

If you take a look at the class CharactersViewModel.kt:

class CharactersViewModel(
    private val getCharacters: GetCharacters
) : ViewModel() {

    // Code

    private val _characters = MutableStateFlow(CharactersScreenState())
    val characters: StateFlow<CharactersScreenState>
        get() = _characters

    // Code

    init {
        getCharacters()
    }

    fun getCharacters(isPaginated: Boolean = false) {
        // Code
    }

	// Code
}

The method getCharacters() will be called as soon as the CharactersViewModel is initialized. Since it is the init block, each time the constructor is called, it is going to be called.

aa