如何在Dager 2中创建包含DAO对象的ViewModel?

时间:2019-03-23 10:57:44

标签: java android mvvm dagger-2

我在Activity中创建了android ViewModel:

EventViewModel model = ViewModelProviders.of(this).get(EventViewModel.class);

为此,我创建了EventViewModel

public class EventViewModel extends ViewModel {

    private final EventDao eventDao;

    public EventViewModel(EventDao eventDao) {
        this.eventDao = eventDao;
    }

    public void createEvent(final Event event) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                eventDao.insert(event);
            }
        }).start();
    }
}

我了解到必须创建自定义工厂才能将EventDao注入EventViewModel。好吧,假设我做到了。

public class ViewModelFactory implements ViewModelProvider.Factory {

    private final EventDao eventDao;

    @Inject
    public ViewModelFactory(EventDao eventDao) {
        this.eventDao = eventDao;
    }


    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass == EventViewModel.class) {
            return (T) new EventViewModel(eventDao);
        }
        return null;
    }
}

但是下一步该怎么做?我看到几种方法。如果相信Google的例子,我必须在MyActivity中下一步:

EventViewModel model = ViewModelProviders.of(this, new ModelFactory(eventDao)).get(EventViewModel.class);

1)但是我在MyActivity中从哪里得到eventDao

2)如果每个ModelFactory使用dao类,是否需要为每个ViewModel创建自定义Dagger 2

我使用ViewModel,我只想了解如何使用DAO创建ViewModel并在MyActivity中使用此vm

1 个答案:

答案 0 :(得分:0)

您将ViewModelFactory注入到活动中。 ViewModelFactory将通过构造函数注入获取EventDao。您将注入的ViewModelFactory实例说 viewModelFactory 传递给ViewModelProviders

EventViewModel model = ViewModelProviders.of(this, viewModelFactory).get(EventViewModel.class);