How to make a singleton for retrofit 2?

后端 未结 5 615
别跟我提以往
别跟我提以往 2021-01-20 18:40

If there exists multiple retrofit call, how can i make a singleton of a retrofit, so that there won\'t be repeated codes within the class, thereby get rid of unnecessary cod

5条回答
  •  无人及你
    2021-01-20 18:42

    i have tried in kotlin :

    class RetrofitClient{
    
        companion object
        {
            var retrofit:Retrofit?=null;
            fun getRetrofitObject():Retrofit?
            {
                if(retrofit==null)
                {
                    synchronized(RetrofitClient ::class.java)
                    {
                        retrofit=Retrofit.Builder()
                            .addConverterFactory(GsonConverterFactory.create())
                            .baseUrl("YOUR_BASE_URL")
                            .build()
                    }
                }
                return retrofit
    
            }
    
        }
    }
    

    and then:

    var service:ServicesInterface?= RetrofitClient.getRetrofitObject()?.create(ServicesInterface::class.java)

提交回复
热议问题