Skip to content

ViewModel VS AndroidViewModel VS hiltViewModel in Android

Published: at 3 min read

Table of contents

Open Table of contents

Difference Among ViewModel, AndroidViewModel and hiltViewModel

ViewModel :

AndroidViewModel :

HiltViewModel :

Example of using AndroidViewModel

public class MainAndroidViewModel extends AndroidViewModel {
    private MutableLiveData<String> data = new MutableLiveData<>();

    public MainAndroidViewModel(Application application) {
        super(application);
        // Initialize data or perform other setup using the application context.
    }

    public LiveData<String> getData() {
        return data;
    }

    public void updateData(String newData) {
        data.setValue(newData);
    }
}

Example of using ViewModel

import androidx.lifecycle.ViewModel;

public class MainViewModel extends ViewModel {
    // ViewModel logic and data storage
}

Example of using hiltViewModel

@HiltViewModel
class MainViewModel @Inject constructor():ViewModel(){
}

In case of JetPack Compose - usage of ViewModel

The standard way of defining a viewModel inside a composable function is by doing the following:

@Composable
fun HomeScreen(navController: NavController) {
    val viewModel: HomeViewModel = viewModel()
}

If viewModel is annotated with @HiltViewModel it could not be added to the navigation graph through the standard way.The hilt-navigation dependency needs to be added:

implementation "androidx.hilt:hilt-navigation-compose:$compose_hilt_navigation_version"

then update the composable function where ViewModel is declared.

@Composable
fun HomeScreen(navController: NavController) {
    val viewModel = hiltViewModel<HomeViewModel>()
}

Ending Note

ViewModels remain a valuable tool for many Android app development scenarios, particularly for separating UI-related concerns from the UI components, ensuring data survives configuration changes, and making UI-related logic testable.

Share :
Written by:Parita Dey

Interested in Writing Blogs, showcase yourself ?

If you're passionate about technology and have insights to share, we'd love to hear from you! Fill out the form below to express your interest in writing technical blogs for us.

If you notice any issues in this blog post or have suggestions, please contact the author directly or send an email to hi@asdevs.dev.