This is how I'm observing data in `MyActivity class:
@Module
public class MyActivity extends DaggerAppCompatActivity {
@Inject MyViewModelFactory factory;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addData();
}
public void addData() {
//How to pass this custom object to ViewModel???
CustomClass obj = new CustomClass("CustomData");
MyViewModel viewModel = ViewModelProviders.of(this, factory).get(MyViewModel.class);
LiveData<Data> liveData = viewModel.getLiveData();
liveData.observe(this, this);
}
}
This my ModelFactory
class:
@Singleton
public class MyViewModelFactory implements ViewModelProvider.Factory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;
@Inject
MyViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
this.creators = creators;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
Provider<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("unknown model class " + modelClass);
}
try {
return (T) creator.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
And this is my ViewModel
class:
public class MyViewModel extends ViewModel {
private LiveData<Data> dataLiveData;
private MyRepository repository;
@Inject
MyViewModel(MyRepository repository) {
this.repository = repository;
//I need it here!!!
dataLiveData = repository.addDataToLiveData(obj);
}
LiveData<Data> getLiveData() {
return dataLiveData;
}
}
And this is my Repository
class:
@Singleton
public class MyRepository {
private MyApi myApi;
@Inject
MyRepository(MyApi myApi) {
this.myApi = myApi;
}
LiveData<Data> addDataToLiveData(CustomClass obj) {
myApi.getData(obj); //Make Api call and use obj
}
}
How to pass that CustomClass
object from MyActivity
to the ViewModel
class?
Make a function in ViewModel that accepts your CustomClass object, and call that function from Activity.
public class MyViewModel extends ViewModel {
private LiveData<Data> dataLiveData;
private MyRepository repository;
@Inject
MyViewModel(MyRepository repository) {
this.repository = repository;
}
LiveData<Data> getLiveData() {
return dataLiveData;
}
public void setCustomObject(CustomObject customObj){
repository.addDataToLiveData(obj);
}
}
EDIT: To fix your error:
public void addData() {
//How to pass this custom object to ViewModel???
CustomClass obj = new CustomClass("CustomData");
MyViewModel viewModel = ViewModelProviders.of(this, factory).get(MyViewModel.class);
//ADD IT HERE
viewModel.setCustomObj(obj);
LiveData<Data> liveData = viewModel.getLiveData();
liveData.observe(this, this);
}