janishar/android-mvvm-architecture

Proper way to inject data into viewModels

Opened this issue · 4 comments

Hello,

I am using this example as template for my own application.
It helped me a great deal trying to understand Dagger2, but ran into a bit of an issue.
I wrote a new module for a client that i need to get data from a local ftp server and added it to the module to AppComponent

Now from wat i understand the ActivityBuilder (also added to AppComponent basicly functions the same as doing void inject(MainActivity activity); in our AppComponent.
Which will allow for data injection into all of the activity's listed in there.

But the client is used for data communication with a small ftp server, all the data get handled in my viewModels so i feel like it makes more sense to directly inject it into there, but i am not sure how or wat even the proper way of doing it would be.

So my question is, based on this application, wat is the proper way to inject something into a viewModel or do i have to pass it like your example shows with the dataManager?
or as last option should i inject it into the activity instead, and use getNavigator to access a get method that fetches the client from the activity ?

Create a provider like BlogFragmentProvider for that class and use it through Activity.

Lovely, let me have a look at that!

Edit, alright so that would mean that i create a provider for every viewModel that needs to be injected with my ftp client? Beccause i need more then 1 view model to access it,

OKe so i tried to make one, And it does work, but very much wondering if its the best approuch, especialy since it needs to be injected in 90% of all the viewmodels i got,
Is it in that case not easyer to write an ViewModelBuilder? and do the same as the ActivityBuilder? where i include all the viewModels that might need it?

Scrap wat i said, i thought i worked, but it was grabbing the value out of my MainActivity still.

Wat i had done after that discovery was this.

@Module
public abstract class MainViewModelProvider {

    @ContributesAndroidInjector(modules = ClientModule.class)
    abstract MainViewModel provideMainViewModel();
}

A provider for my MainViewModel and gave it the ClientModule class as module (class that makes a singleton of my Client.

and added to my ActivityBuilder


    @ContributesAndroidInjector (modules = {
            MainViewModelProvider.class
    })
    abstract MainViewModel bindMainViewModel();

But this breaks Dagger compleetly, i am clearly not understanding it fully yet, and doing something compleetly wrong.
Could you possibly shine some light on it?