2

I'm new to android development, i need to inject WorkManager for using kodein but i don't know where to start it

this is how to inject activities

class MyActivity : Activity(), KodeinAware {

override val kodein by kodein() 

val ds: DataSource by instance()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    ds.connect() 
    /* ... */
   }

}

this is my worker i need to get the instance of Appdatabase for using kodein but it didn't work for me

class MyWorker(context: Context, params: WorkerParameters) :
    CoroutineWorker(context, params), KodeinAware {

    override val kodein by kodein()


    private val db: AppDatabase by instance()

    override suspend fun doWork(): Result = withContext(IO) {
        try {
            //do the work
            Result.success()
        } catch (e: Exception) {
            Result.retry()
          }
       }

   }

Binding the AppDatabase

class AppBase : Application(), KodeinAware {

    override val kodein = Kodein.lazy {
    import(androidXModule(this@AppBase))
    bind() from singleton { AppDatabase.getInstance(instance())}
  }
}
ismacil jama
  • 69
  • 1
  • 7

1 Answers1

3

Not sure your code even compiles...

Regarding to your Worker class:

class MyWorker(context: Context, params: WorkerParameters) :
    CoroutineWorker(context, params), KodeinAware {

    override val kodein by kodein()
    // ...
}

As far as I saw, there is no such method as kodein() for the CoroutineWorker. Thus, this is not working. But, as you have a Context, you could use the following code to get your Kodein container:

class MyWorker(context: Context, params: WorkerParameters) :
    CoroutineWorker(context, params), KodeinAware {

    override val kodein by kodein { context }
    // ...
}

Let us know if this works for you. (Otherwise post the error you get).

romainbsl
  • 534
  • 3
  • 10
  • also you could use `override val kodein: Kodein by closestKodein { context }` – epool Apr 01 '20 at 14:04
  • Yes but this one calls the one I’d put in my answer. Also it’s in deprecation circle, thus it will be remove soon – romainbsl Apr 01 '20 at 18:23