Skip to content
This repository has been archived by the owner on Apr 20, 2021. It is now read-only.

Use Dagger2 injected objects in Plugin #61

Closed
markusressel opened this issue Feb 16, 2018 · 3 comments
Closed

Use Dagger2 injected objects in Plugin #61

markusressel opened this issue Feb 16, 2018 · 3 comments

Comments

@markusressel
Copy link

Hi,

I really like this library and it has brought some great improvements into my code. Thanks :-)
However I'm facing a challenge now:

I'm using Dagger2 as a dependency injection framework in my app.
I have a (CompositeAndroid) plugin that needs to have access to some injected classes.
However since plugins are added in the constructor of an Activity (or Fragment) and fields are injected in onCreate() of the root base Activity it is not possible to access injected fields on construction so I cannot pass it as a parameter to the plugin from the Activity.

Example:

abstract class LockableSupportActivityBase : DaggerSupportActivityBase() {

    @Inject
    protected lateinit var preferenceHandler: PreferenceHandler

    init {
        // this throws NotInitializedException on "preferenceHandler"
        addActivityPlugins(LockPlugin(preferenceHandler))
    }

}

Injecting the Plugin itself is also not possible since it has to be added to the Activity in the constructor and the activity also has access to injected properties only right after super.onCreate() (so it's too late).

Example:

abstract class LockableSupportActivityBase : DaggerSupportActivityBase() {

    @Inject
    protected lateinit var lockPlugin: LockPlugin

    init {
        // this throws NotInitializedException on "lockPlugin"
        addActivityPlugins(lockPlugin)
    }

}

Is there a way to work around this or is this a problem that needs a more sophisticated fix?

@passsy
Copy link
Owner

passsy commented Feb 16, 2018

instead of passing the object directly into your plugin you could pass a method returning the object.

class LockPlugin(val preferenceHandlerProvider: ()-> PreferenceHandler) : ActivityPlugin { ... }
    init {
        addActivityPlugins(LockPlugin( { preferenceHandler } ))
    }

@markusressel
Copy link
Author

Ah that's a great idea!
Thanks for the quick reponse.
I will try it tomorrow though since it's 4 a clock in the morning around here... :D

@markusressel
Copy link
Author

It works!

Although it's kind of a workaround it's not that bad so I can live with it.

Thx for the quick help :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants