我的每个API服务接口类都有创建静态方法
interface AuthApiService {
@FormUrlEncoded
@POST("api/auth/login")
fun postLogin(@Field("username") username: String, @Field("password") password: String):
io.reactivex.Observable<LoginApiResponse>
companion object Factory {
fun create(): AuthApiService {
val gson = GsonBuilder().setLenient().create()
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("http:192.168.24.188:8080")
.build()
return retrofit.create(AuthApiService::class.java)
}
}
}
interface BBBApiService {
companion object Factory {
fun create(): BBBApiService {
val gson = GsonBuilder().setLenient().create()
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("http:192.168.24.188:8080")
.build()
return retrofit.create(BBBApiService::class.java)
}
}
}
但是,我想只定义一次create()方法。
所以我做了ApiFactory类,
interface ApiFactory {
companion object {
inline fun <reified T>createRetrofit(): T {
val gson = GsonBuilder().setLenient().create()
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("http://192.168.24.188:8080")
.build()
return retrofit.create(T::class.java)
}
}
}
interface AuthApiService {
@FormUrlEncoded
@POST("api/auth/login")
fun postLogin(@Field("username") username: String, @Field("password") password: String):
io.reactivex.Observable<LoginApiResponse>
companion object Factory {
fun create(): AuthApiService {
return ApiFactory.createRetrofit()
}
}
但是,我仍然需要在AuthApiService中定义create()方法。
有没有办法将ApiFactory类实现到SubApi类,这样我就不必在每个子类中定义create方法了?
答案 0 :(得分:3)
一个简单的解决方案就是直接调用ApiFactory
的功能:
val authApiService = ApiFactory.createRetrofit<AuthApiService>()
但是,如果您希望能够拨打AuthApiService.create()
,那么您可以定义标记界面,例如ApiFactoryClient<T>
,并用它标记空companion object
。
interface ApiFactoryClient<T>
interface AuthApiService {
/* ... */
companion object : ApiFactoryClient<AuthApiService>
}
然后创建一个适用于ApiFactoryClient<T>
的扩展函数:
inline fun <reified T> ApiFactoryClient<T>.create(): T = ApiFactory.createRetrofit<T>()
用法是:
val authApiService = AuthApiService.create()
答案 1 :(得分:2)
您可以像这样修改ApiFactory
:
interface ApiFactory {
companion object {
inline fun <reified T>createRetrofit(klass: KClass<T>): T {
val gson = GsonBuilder().setLenient().create()
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("http://192.168.24.188:8080")
.build()
return retrofit.create(klass.java)
}
}
}
然后使用它来创建不同的服务实例:
val authApiService = ApiFactory.createRetrofit(AuthApiService::class)