Koin. Cannot inject to fragment with ScopeActivity

967 views Asked by At

I'm trying to inject some dependency to both activity and fragment using Koin and I expect it to live as long as activity lives, but it turned out a headache for me.

I managed to create a module that resolves MainRouter, inject it into an activity, but it doesn't work for a fragment.

val appModule = module {
    scope<MainActivity> {
        scoped { MainRouter() }
    }
}

MainActivity extends ScopeActivity, MyFragment extends ScopeFragment.

in MainActivity private val router : MainRouter by inject() works fine, but in MyFragment it throws org.koin.core.error.NoBeanDefFoundException: No definition found for class:'com.example.app.MainRouter'. Check your definitions!

Finally I managed to inject, but it doesn't look pretty

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val scopeId = scopeActivity!!.getScopeId()
    scope.linkTo(getKoin().getScope(scopeId))
    mainRouter = get()
    ...

I also don't like that scopeActivity can't be accessed in the init method. Does this mean that activity scoped dependencies cannot be resolved in fragment using by inject()?

1

There are 1 answers

4
Pratik Satani On

As I can see in your code, you have to declare a Fragment instance, just declare it as a fragment in your Koin module and use constructor injection. Like below:

    val appModule = module {
    single { MyService() }
    fragment { MyFragment(get()) }
}

Please refer link for more details.