我試圖遵循google()的示例。我看到它可以綁定到不同的ViewModel類型到通用類型。如何使用Dagger2綁定到具有多個ViewModelFactory的地圖
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(UserViewModel.class)
abstract ViewModel bindUserViewModel(UserViewModel userViewModel);
@Binds
@IntoMap
@ViewModelKey(SearchViewModel.class)
abstract ViewModel bindSearchViewModel(SearchViewModel searchViewModel);
@Binds
@IntoMap
@ViewModelKey(RepoViewModel.class)
abstract ViewModel bindRepoViewModel(RepoViewModel repoViewModel);
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(GithubViewModelFactory factory);
}
我想要做的就是多ViewModelProvider.Factory綁定到通用之一。
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelFactoryKey(FeedEntryListViewModelFactory.class)
abstract ViewModelProvider.Factory bindViewModelFactory(FeedEntryListViewModelFactory factory);
}
ViewModelFactoryKey.java
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface ViewModelFactoryKey {
Class<? extends ViewModelProvider.Factory > value();
}
FeedActivity.java
public class FeedActivity extends DaggerAppCompatActivity {
@Inject
ViewModelProvider.Factory viewModelFactory;
FeedEntryListViewModel viewModel;
@SuppressLint("StaticFieldLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
...
}
}
然而,它引發以下錯誤。
Error:(21, 8) error: [dagger.android.AndroidInjector.inject(T)] android.arch.lifecycle.ViewModelProvider.Factory cannot be provided without an @Provides- or @Produces-annotated method.
android.arch.lifecycle.ViewModelProvider.Factory is injected at
com.cn29.aac.ui.feedentry.FeedActivity.viewModelFactory
com.cn29.aac.ui.feedentry.FeedActivity is injected at
dagger.android.AndroidInjector.inject(arg0)
我是Dagger2的新手。如果使用不當,請隨時發表評論。謝謝。
'我想要做的就是多ViewModelProvider.Factory綁定到通用one' - 這是什麼意思?你有各種工廠,你想把它們放到地圖上? – azizbekian
是的,我想要它。其實我有多個類FeedListViewModelFactory,FeedDetailViewModelFactory ...但在這些活動中,注入類型是ViewModelProvider.Factory。因此,我需要將兩者都映射到ViewModelProvider.Factory。 –