Kodein returns a new instance instead of singleton

322 Views Asked by At

I'm new to Kodein and I've got this simple module :

import com.myapp.MyApplication.Companion.INSTANCE
import com.facebook.flipper.android.AndroidFlipperClient
import com.facebook.flipper.core.FlipperClient
import com.facebook.flipper.plugins.inspector.DescriptorMapping
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin
import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.kodein.di.Kodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import org.kodein.di.generic.singleton

const val FLIPPER_MODULE_TAG = "FLIPPER_MODULE_TAG"

val flipperModule = Kodein.Module(FLIPPER_MODULE_TAG) {
    bind<NetworkFlipperPlugin>() with singleton {
        NetworkFlipperPlugin()
    }

    bind<FlipperClient>() with singleton {
        val networkFlipperPlugin: NetworkFlipperPlugin = instance()
        val client: FlipperClient = AndroidFlipperClient.getInstance(INSTANCE.baseContext)
        val inspectorFlipperPlugin =
            InspectorFlipperPlugin(INSTANCE, DescriptorMapping.withDefaults())
        client.addPlugin(networkFlipperPlugin)
        client.addPlugin(inspectorFlipperPlugin)
        client
    }

    bind<HttpClient>() with singleton {
        val logging = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
        val networkFlipperPlugin: NetworkFlipperPlugin = instance()
        val okHttpClientInstance = OkHttpClient.Builder().addNetworkInterceptor(FlipperOkhttpInterceptor(networkFlipperPlugin)).build()

        val httpClient = HttpClient(OkHttp) {
            engine {
                addInterceptor(logging)
                preconfigured = okHttpClientInstance
            }
        }
        httpClient
    }
}

The problem is that

val networkFlipperPlugin: NetworkFlipperPlugin = instance()

always returns a new instance instead of a singleton (actually all my singletons returns a new instance everytime I retrieve them)

Any leads on that ? Thanks a lot !

1

There are 1 best solutions below

0
On

I overlooked the piece of code in my activity :

 override val kodein: Kodein by retainedKodein {
        extend(parentKodein, copy = Copy.All)
    }

As I said, I'm new to Kodein :)