Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

android - ViewModelProviders with Dagger 2, not able to grasp the concept

I have a Retrofit Service like this

public interface BrandsService {
    @GET("listBrand")
    Call<List<Brand>> getBrands();
}

Then I have a Repository to get data from an api like this

public class BrandsRepository {
    public static final String TAG = "BrandsRepository";
    MutableLiveData<List<Brand>> mutableLiveData;
    Retrofit retrofit;

    @Inject
    public BrandsRepository(Retrofit retrofit) {
        this.retrofit = retrofit;
    }

    public LiveData<List<Brand>> getListOfBrands() {
//       Retrofit retrofit = ApiManager.getAdapter();
        final BrandsService brandsService = retrofit.create(BrandsService.class);
        Log.d(TAG, "getListOfBrands: 00000000000 "+retrofit);

        mutableLiveData = new MutableLiveData<>();

        Call<List<Brand>> retrofitCall = brandsService.getBrands();
        retrofitCall.enqueue(new Callback<List<Brand>>() {
            @Override
            public void onResponse(Call<List<Brand>> call, Response<List<Brand>> response) {
                mutableLiveData.setValue(response.body());
            }

            @Override
            public void onFailure(Call<List<Brand>> call, Throwable t) {
                t.printStackTrace();
            }
        });
        return mutableLiveData;

    }
}

I am using constructor injection of Dagger2 by injecting Retrofit like that. Then I have a ViewModel like this

public class BrandsViewModel extends ViewModel{
    BrandsRepository brandsRepository;
    LiveData<List<Brand>> brandsLiveData;
    @Inject
    public BrandsViewModel(BrandsRepository brandsRepository) {
        this.brandsRepository = brandsRepository;
    }

    public void callService(){
       brandsLiveData = brandsRepository.getListOfBrands();
    }

    public LiveData<List<Brand>> getBrandsLiveData() {
        return brandsLiveData;
    }


}

To inject Retrofit in BrandsRepository, I have to inject BrandsRepository like that. Then I have MainActivity like this

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    @Inject
    BrandsViewModel brandsViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((MainApplication)getApplication()).getNetComponent().inject(this);

//        BrandsViewModel brandsViewModel = ViewModelProviders.of(this).get(BrandsViewModel.class);
        brandsViewModel.callService();

        LiveData<List<Brand>> brandsLiveData = brandsViewModel.getBrandsLiveData();
        brandsLiveData.observe(this, new Observer<List<Brand>>() {
            @Override
            public void onChanged(@Nullable List<Brand> brands) {
                Log.d(TAG, "onCreate: "+brands.get(0).getName());
            }
        });


    }
}

The BrandsViewModel is injected using Dagger2 rather than ViewModelProviders. This is working fine but when I try to use ViewModelProviders by uncommenting it, dagger gives me the error which is obvious. The proper way of getting a ViewModel is by using ViewModelProviders but how will I accomplish this while injecting retrofit like that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: An important note. To use Jetpack ViewModel, you don't need map-multibinding. Read on.


The answer can be simpler than Mumi's approach, which is that you expose the ViewModel on your component:

@Singleton
@Component(modules={...})
public interface SingletonComponent {
    BrandsViewModel brandsViewModel();
}

And now you can access this method on the component inside the ViewModelFactory:

// @Inject
BrandsViewModel brandsViewModel;

...
brandsViewModel = new ViewModelProvider(this, new ViewModelProvider.Factory() {
    @Override
    public <T extends ViewModel> create(Class<T> modelClazz) {
        if(modelClazz == BrandsViewModel.class) {
            return singletonComponent.brandsViewModel();
        }
        throw new IllegalArgumentException("Unexpected class: [" + modelClazz + "]");
    }).get(BrandsViewModel.class);

All this can be simplified and hidden with Kotlin:

inline fun <reified T: ViewModel> AppCompatActivity.createViewModel(crossinline factory: () -> T): T = T::class.java.let { clazz ->
    ViewModelProvider(this, object: ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if(modelClass == clazz) {
                @Suppress("UNCHECKED_CAST")
                return factory() as T
            }
            throw IllegalArgumentException("Unexpected argument: $modelClass")
        }
    }).get(clazz)
}

which now lets you do

brandsViewModel = createViewModel { singletonComponent.brandsViewModel() }

Where now BrandsViewModel can receive its parameters from Dagger:

class BrandsViewModel @Inject constructor(
    private val appContext: Context,
    /* other deps */
): ViewModel() {
    ...
}

Though the intent might be cleaner if a Provider<BrandsViewModel> is exposed from Dagger instead

interface SingletonComponent {
    fun brandsViewModel(): Provider<BrandsViewModel>
}

brandsViewModel = createViewModel { singletonComponent.brandsViewModel().get() }

With some additional trickery coming in from android-ktx, you could even do

@Suppress("UNCHECKED_CAST")
inline fun <reified T : ViewModel> Fragment.fragmentViewModels(
    crossinline creator: () -> T
): Lazy<T> {
    return createViewModelLazy(T::class, storeProducer = {
        viewModelStore
    }, factoryProducer = {
        object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(
                modelClass: Class<T>
            ): T = creator.invoke() as T
        }
    })
}

And then

class ProfileFragment: Fragment(R.layout.profile_fragment) {
    private val viewModel by fragmentViewModels {
        singletonComponent.brandsViewModelFactory().get()
    }

Where brandsViewModelFactory() is

fun brandsViewModelFactory(): Provider<BrandsViewModel>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

56.9k users

...