简体   繁体   中英

Kotlin Dagger Module not set

New to kotlin and trying to migrate over a small Android project written in Java. Don't know what to make of this error:

Caused by: java.lang.IllegalStateException:
com.mydomain.example.dagger.BusModule must be set
> at com.mydomain.example.dagger.DaggerAppComponent$Builder.build(DaggerAppComponent.java:87)
> at com.mydomain.example.MyApplication.buildComponent(MyApplication.kt:29)
> at com.mydomain.example.MyApplication.onCreate(MyApplication.kt:17)
> at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1118)
> at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5791)

Here is the BusModule class:

@Module
object BusModule {

    const val PROVIDER_FRAGMENT_SELECTION = "fragment_selection"

    @Provides
    @Singleton
    @Named(PROVIDER_FRAGMENT_SELECTION)
    fun provideNewFragmentSelection(): PublishSubject<String> {
        return PublishSubject.create()
    }
}

And here is the AppComponent class:

@Component(modules = [(AppModule::class), (DataModule::class), (BusModule::class)])
@Singleton
interface AppComponent {

    @get:Named(BusModule.PROVIDER_FRAGMENT_SELECTION)
    val selectedFragmentName: PublishSubject<String>

    fun inject(mainActivity: MainActivity)
}

And finally, the application class:

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        appComponent = buildComponent()
    }

    private fun buildComponent(): AppComponent {
        return DaggerAppComponent.builder().build()
    }

    companion object {

        var appComponent: AppComponent? = null
            private set
    }
}

Can't figure out what the error message means. How is the BusModule not 'set'? Thanks!

BusModule should be a class instead of an object and const val PROVIDER_FRAGMENT_SELECTION should be moved to companion object of the class. So the module becomes:

@Module
class BusModule {
    companion object {
        const val PROVIDER_FRAGMENT_SELECTION = "fragment_selection"
    }
    @Provides
    @Singleton
    @Named(PROVIDER_FRAGMENT_SELECTION)
    fun provideNewFragmentSelection(): PublishSubject<String> {
        return PublishSubject.create()
    }
}

I think all you would have had to do was add a @JvmStatic annotation.

@Module
object BusModule {
    @Provides
    @Singleton
    @Named(PROVIDER_FRAGMENT_SELECTION)
    @JvmStatic
    fun provideNewFragmentSelection(): PublishSubject<String> {
        return PublishSubject.create()
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM