Skip to content Skip to sidebar Skip to footer

How To Pass A String To A Viewmodel/repository Class Using Dagger2 In Android?

This is my fragment class: public class MyFragment extends DaggerFragment { @Inject MyViewModelFactory factory; @Nullable @Override public View onCreateView(Layout

Solution 1:

A possible solution is to have 1 factory per viewmodel, then you set the UID to the factory and the factory passes it to the viewmodel

classMyViewModelFactory@Injectconstructor(
        privateval repository: Repository
): ViewModelProvider.Factory {

    lateinitvar uid: String

    @Suppress("UNCHECKED_CAST")overridefun<T : ViewModel>create(modelClass: Class<T>): T =
            if (modelClass.isAssignableFrom(MyViewModel::class.java)) {
                    MyViewModel(
                        repository,
                        uid
                ) as T
            } else {
                throw IllegalArgumentException("Unknown ViewModel class [$modelClass]")
            }
}

then

@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    Stringuid="123"; //How to pass this String??
    factory.setUid(uid);
    MyViewModelviewModel= ViewModelProviders.of(this, factory).get(MyViewModel.class);
    LiveData<User> liveData = viewModel.getUserLiveData();
}

Edit: in Java

publicfinalclassMyViewModelFactoryimplementsFactory {
    privatefinal Repository repository;
    private String uid;

   @InjectpublicMyViewModelFactory(Repository repository) {
      this.repository = repository;
   }

   @NotNullpublic ViewModel create(@NotNull Class modelClass) {
      if (modelClass.isAssignableFrom(MyViewModel.class)) {
         returnnewMyViewModel(repository, uid);
      } else {
         throw (Throwable)(newIllegalArgumentException("Unknown ViewModel class [" + modelClass + ']'));
      }
   }

   publicvoidsetUid(@NonNullfinal String uid) {
       this.uid = uid;
   }
}

@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    Stringuid="123"; //How to pass this String??
    factory.setUid(uid);
    MyViewModelviewModel= ViewModelProviders.of(this, factory).get(MyViewModel.class);
    LiveData<User> liveData = viewModel.getUserLiveData();
}

Post a Comment for "How To Pass A String To A Viewmodel/repository Class Using Dagger2 In Android?"