class SlideshowViewModel : ViewModel() {
@Inject lateinit var mediaItemRepository : MediaItemRepository
fun init() {
What goes here?
}
所以我試圖學習Dagger2,這樣我就可以讓我的應用程序更具可測試性。問題是,我已經集成了Kotlin,並且正在開發Android架構組件。我明白建設者注入是可取的,但這是ViewModel
不可能的。相反,我可以使用lateinit
來注入,但我很難弄清楚如何注入。使用Dagger注入ViewModel 2 + Kotlin + ViewModel
我需要爲SlideshowViewModel
創建一個Component
,然後注入它嗎?或者我使用Application
組件?
gradle這個:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
kapt {
generateStubs = true
}
dependencies {
compile "com.google.dagger:dagger:2.8"
annotationProcessor "com.google.dagger:dagger-compiler:2.8"
provided 'javax.annotation:jsr250-api:1.0'
compile 'javax.inject:javax.inject:1'
}
應用程序組件
@ApplicationScope
@Component (modules = PersistenceModule.class)
public interface ApplicationComponent {
void injectBaseApplication(BaseApplication baseApplication);
}
BaseApplication
private static ApplicationComponent component;
@Override
public void onCreate() {
super.onCreate();
component = DaggerApplicationComponent
.builder()
.contextModule(new ContextModule(this))
.build();
component.injectBaseApplication(this);
}
public static ApplicationComponent getComponent() {
return component;
}
「所以我試圖學習匕首2,所以我可以讓我的應用程序更可測試」 - 我會說匕首2對可測試性沒有影響,或者它的影響過小。 如果這是唯一的原因,你可能想要傳遞它。 *作爲Dagger的用戶發佈了很多關於它的教程 – Vasiliy
不是你的問題的答案,但你忘了在你的'build.gradle'文件中應用插件:'kotlin-kapt''。另外,你應該使用'kapt'而不是'annotationProcessor'。 – Benjamin