2

want to initialize interface in a non activity or fragment class with Kodein DI Android

sample shows only hot to use Kodein inside activity, but not on the other parts

 class MainViewModel() :  KodeinAware{
   override val kodein by closestKodein()
   val repository : Repository by instance()
 }

in activity it works, but in other classes it shows error. I want to initialize interface inside another class

Nurseyit Tursunkulov
  • 8,012
  • 12
  • 44
  • 78

5 Answers5

1

closestKodein only works in Android Context aware classes (such as fragments & activities). To use it outside of these classes, you need an Android context.

The android documentation clearly states:

Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

[...]

If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.

Therefore, to access Kodein from a ViewModel:

class MainViewModel(app: Application) : ApplicationViewModel(app), KodeinAware {
    override val kodein = app.kodein
    val repository : Repository by instance()
}
Community
  • 1
  • 1
Salomon BRYS
  • 9,247
  • 5
  • 29
  • 44
1

Simpy pass a context or activity as param

override val kodein by closestKodein(context)

More info https://kodein.org/Kodein-DI/?5.0/android#_getting_a_kodein_object

Vlad
  • 7,997
  • 3
  • 56
  • 43
1

Use it in any place. appKodein is global function.

val dataLayer: DataLayer = appKodein().instance()
Pavel Shorokhov
  • 4,485
  • 1
  • 35
  • 44
0

override val kodein by kodein(activity!!)

Don
  • 3,876
  • 10
  • 47
  • 76
Sharanjeet Kaur
  • 796
  • 13
  • 18
0
class ReportViewModel(context: Context):ViewModel() ,KodeinAware
{
override val kodein by kodein(context)
val reportRepository:ReportRepository by instance()
}

My answer