1. 程式人生 > >Kotlin單列模式封裝Retrofit

Kotlin單列模式封裝Retrofit

class RetrofitUtils private constructor() {
    val C_TIME: Long = 15
    val W_TIME: Long = 15
    val R_TIME: Long = 15
    var retrofit: Retrofit? = null

    //kotlin實現
    companion object {
        val getInstance: RetrofitUtils by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            RetrofitUtils()
        }
    }
    //--獲取到retrofit
    fun   sinitRetrofit(): Retrofit {
        if (retrofit == null) {
            synchronized(Retrofit::class.java) {
                if (retrofit == null) {
                    retrofit = Retrofit.Builder()
                            .baseUrl(HttpUrl.Url)
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .client(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                                    .connectTimeout(C_TIME, TimeUnit.SECONDS)
                                    .writeTimeout(W_TIME, TimeUnit.SECONDS)
                                    .readTimeout(R_TIME, TimeUnit.SECONDS)
                                    .build()
                            ).build()

                }

            }

        }

        return retrofit!!
    }

}