Reputation: 6743
I just started learning dependendy injection with Koin. Here's my repo: https://github.com/anta40/DIWithKoin
Here's the overview. First create a SessionManager class which stored and reads a string value:
import android.content.Context
import android.content.SharedPreferences
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
val sessionModule = module {
single { SessionManager(androidContext()) }
}
class SessionManager (context: Context) {
private val preferences: SharedPreferences = context.getSharedPreferences("app_pref", Context.MODE_PRIVATE)
private val MY_CUSTOM_STR = "test"
init {
saveStringValue("Hello world 12345")
}
private fun saveStringValue(content: String) {
preferences.edit().putString(MY_CUSTOM_STR, content).apply()
}
fun getStringValue(): String? {
return preferences.getString(MY_CUSTOM_STR, "")
}
}
Then use Koin to inject the SessionManager class to MainActivity:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.anta40.app.diwithkoin.databinding.ActivityMainBinding
import org.koin.android.ext.android.inject
class MainActivity : AppCompatActivity() {
private val session: SessionManager by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Should print "Hello world 12345"
binding.txtValue.text = session.getStringValue()
}
}
It crashes, though. Found this error on logcat:
Process: com.anta40.app.diwithkoin, PID: 6423 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.anta40.app.diwithkoin/com.anta40.app.diwithkoin.MainActivity}: org.koin.core.error.NoBeanDefFoundException: No definition found for class:'com.anta40.app.diwithkoin.SessionManager'. Check your definitions!
What am I missing?
Upvotes: 2
Views: 3848
Reputation: 8447
You have to declare the singleton or the factory method on how to get the SessionManager
Typically you do this from the onCreate
in your Application
class:
class YourApp : Application() {
override fun onCreate() {
startKoin {
androidContext(app)
androidLogger()
val modules = listOf(
module {
/*or however you construct it*/
factory<SessionManager>{ SessionManager(get()) }
}
)
loadKoinModules(modules)
}
}
}
The sample provided was using koin 2.1.5
Upvotes: 2