Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use koin but doesnt work correctly on android

I'm trying to implement Koin in my project. So far, I did this:

My shared preferences class:

class MPCUtilSharedPreference(private val sharedPreferences: SharedPreferences{}

I want to inject that class in other classes. So, I create my MainApplication class:

class MPCMainApplication : Application() {

override fun onCreate() {
    super.onCreate()
    startKoin {
        androidContext(this@MPCMainApplication)
        modules(modules)
    }
}

}

This is my module class:

private val appModule = module {
single {
    MPCUtilSharedPreference(
        androidContext().getSharedPreferences(
            BuildConfig.APP_PREFERENCE,
            Context.MODE_PRIVATE
        )
    )
  }
}
val modules = listOf(appModule)

And the I'm trying to inject it:

class MPCNetworkInterceptor : Interceptor {

private val utilSharedPreferences: MPCUtilSharedPreference by inject() }

The error says:

No value passed for parameter 'clazz'

I'm trying to use

import org.koin.android.ext.koin.androidContext

But the AS uses

import org.koin.java.KoinJavaComponent.inject

This is my gradle:

implementation 'org.koin:koin-android:2.1.5'
implementation 'org.koin:koin-androidx-scope:2.1.5'
implementation 'org.koin:koin-androidx-viewmodel:2.1.5'
implementation 'org.koin:koin-androidx-fragment:2.1.5'

Any idea about what's the problem here?

like image 546
CodeAlo Avatar asked Dec 22 '22 18:12

CodeAlo


2 Answers

You're trying to use by inject() delegate from an place that is neither an Activity nor Fragment, that's why the IDE is importing :

import org.koin.java.KoinJavaComponent.inject

If you want to use MPCUtilSharedPreference from MPCNetworkInterceptor, you can pass it as parameter in MPCNetworkInterceptor constructor. And obviously, add this in your module.

Otherwise, you could implement KoinComponent

like image 56
Oscar Sequeiros Avatar answered Jan 14 '23 18:01

Oscar Sequeiros


I dont know, why koin is not able to suggest org.koin.android.ext.android.inject path when using by inject() but I fixed this issue with below code snippet:

private val foo: FooClass by KoinJavaComponent.inject(FooClass::class.java)
like image 27
EKREM YİĞİT Avatar answered Jan 14 '23 17:01

EKREM YİĞİT