Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create ViewModel and inject repository to it with dagger 2?

I try understanding ViewModel. I create ViewModel:

public class UsersViewModel extends ViewModel {

    private final UsersRepository usersRepository;

    public UsersViewModel(UsersRepository usersRepository) {
        this.usersRepository = usersRepository;
    }

    public LiveData<List<User>> loadAll() {
        return usersRepository.getAll();
    }

}

But I not understand 2 things:

  1. How can I inject UsersRepository to this VievModel? When I used presenter I can create it with dagger 2 like this:
@Module
public class PresentersModule {

    @Singleton
    @Provides
    UsersPresenter provideUsersPresenter(UsersRepository usersRepository) {
        return new UsersPresenter(usersRepository);
    }
}

but how can I do it with ViewModel? Like this?

@Module
public class ViewModelsModule {

    @Singleton
    @Provides
    UsersViewModel provideUsersViewModel(UsersRepository usersRepository) {
        return new UsersViewModel(usersRepository);
    }
}
  1. How can I get this ViewModel in fragment? With presenter I can this:

    presenter = MyApplication.get().getAppComponent().getUsersPresenter();

like image 978
ip696 Avatar asked Jul 08 '18 12:07

ip696


1 Answers

Dagger2 required you to create ViewModelModule and do the binding to your ViewModels

I know you are asking about Dagger2, but if you are starting a new project, maybe you can check out Koin which provides a lightweight injection.

I've used it in some of my production apps and it works fine with lesser lines of code.

You can just declare in your module like

viewModel { MyViewModel(get()) }

Then in your activities / fragments / classes (you need to extend KoinComponent), just write

val myViewModel : MyViewModel by viewModel()

It will handle the creation itself.

For more information can refer

https://insert-koin.io/

https://start.insert-koin.io/#/getting-started/koin-for-android?id=android-viewmodel

like image 122
veeyikpong Avatar answered Sep 23 '22 20:09

veeyikpong