0

我是 Kodein 的新手,我有这个简单的模块:

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
    }
}

问题是

val networkFlipperPlugin: NetworkFlipperPlugin = instance()

总是返回一个新实例而不是单例(实际上我所有的单例每次检索它们时都会返回一个新实例)

有什么线索吗?非常感谢 !

4

1 回答 1

0

我忽略了我活动中的一段代码:

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

正如我所说,我是 Kodein 的新手 :)

于 2020-04-11T11:27:40.483 回答