Search code examples
androiddependency-injectionkotlinkodein

kodein - data's value injected are not data's value retrieve


In my CallType class, i put my injected data connectivityState.callBackState to true, which is initialized to false in my ConnectivitySte class. But in my IncomingCallBroadcastReceiver class, my boolean data callBackState is not true but false.

class CallType {

val kodein = Kodein {
    bind<ConnectivityState>() with provider { ConnectivityState() }
}

private val connectivityState: ConnectivityState = kodein.instance()

fun call(number: String) {

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\
connectivityState.callBackState = true
}    


class IncomingCallBroadcastReceiver : KodeinBroadcastReceiver() {

   private val connectivityState: ConnectivityState by instance()

   override fun onBroadcastReceived(context: Context, intent: Intent) {
   
   //!!!!!!!!!!!!!!  IT'S FALSE HERE WHEREAS I PUT IT TO TRUE IN CALLTYPE CLASS
   if (connectivityState.callBackState) {
    }
}    

class ConnectivityState {
   var iaxState = false    
}

Solution

  • The problem lies here:

    bind<ConnectivityState>() with provider { ConnectivityState() }
    

    You are binding to a provider scope, which means that a new instance will be returned every time you ask for an instance.

    If you want the same instance to be returned every time, you need to bind to a singleton:

    bind<ConnectivityState>() with singleton { ConnectivityState() }