如何在Kotlin中实现与多个接口共享的Singleton Retrofit实例

时间:2019-03-09 08:07:55

标签: android kotlin retrofit retrofit2

我有一个eval API,该API返回带有login的客户端,并将其存储在SharedPreferences中。在authToken之后,所有其他API都需要来自SharedPreferences的login。因此,我当前的实现具有2个改造服务接口,如下所示:

authToken返回UserDataService

authToken

interface UserDataService { @PUT("login") fun loginUser(@Body user: UserLoginRequest): Observable<Response<User>> companion object { // for Logging private val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } private val client: OkHttpClient = OkHttpClient.Builder().apply { addInterceptor(interceptor) }.build() val retrofit: UserDataService = Retrofit.Builder() .baseUrl("${URL}/users/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create()) .client(client) .build() .create(UserDataService::class.java) } } 供用户在应用程序中发布,我使用PostDataService在所有与Post相关的API调用中添加了intercepter

authToken

对于我来说,当前的实现似乎没有经过优化,因为每次从这两个接口中的任何一个调用interface PostDataService { @GET(".") fun getPosts( @Query(value = "offset") offset: Int = 0, @Query(value = "limit") limit: Int = 10, @Query(value = "subscribedOnly") subscribedOnly: Boolean = false ): Observable<List<Post>> companion object { // for Logging private val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } private val client = OkHttpClient.Builder().addInterceptor(object : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val newRequest = chain.request().newBuilder() .addHeader( "Authorization", "Bearer ${SharedPreferenceService.getToken(UrekaLiteApplication.context)}" ) .addHeader("Content-Type", "application/json") .build() return chain.proceed(newRequest) } }).addInterceptor(interceptor).build() val retrofit: PostDataService = Retrofit.Builder() .baseUrl("${URL}/post/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create()) .client(client) .build() .create(PostDataService::class.java) } } 时都会创建改造实例。另外,这两个接口也被分隔开,我的意思是,它们不使用同一改造实例。有没有办法只创建一次改造单例一次,并在多个改造接口中使用它?

0 个答案:

没有答案