我在将这个 retrofit 类翻译成 Kotlin 的过程中遇到了困难。它基本上是一个作为客户端的单例,但我不确定我的 Kotlin 实现是否正确。UserAPI 和 ProfileAPI 只是接口。
public class RetrofitService {
private static final String BASE_URL = "https://test.api.com/";
private ProfileAPI profileAPI;
private UserAPI userAPI;
private static RetrofitService INSTANCE;
/**
* Method that returns the instance
* @return
*/
public static RetrofitService getInstance() {
if (INSTANCE == null) {
INSTANCE = new RetrofitService();
}
return INSTANCE;
}
private RetrofitService() {
Retrofit mRetrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
profileAPI = mRetrofit.create(ProfileAPI.class);
UserAPI = mRetrofit.create(UserAPI.class);
}
/**
* Method that returns the API
* @return
*/
public ProfileAPI getProfileApi() {
return profileAPI;
}
/**
* Method that returns the API
* @return
*/
public UserAPI getUserApi() {
return userAPI;
}
}
这是我的 Kotlin 实现。据我理解,当类被实例化时,init 代码块将首先被执行。
class RetrofitService private constructor() {
/**
* Method that returns the API
* @return
*/
private val profileApi: ProfileAPI
private val userAPI: UserAPI
companion object {
private const val BASE_URL = "https://test.api.com/"
private var INSTANCE: RetrofitService? = null
/**
* Method that returns the instance
* @return
*/
fun getInstance(): RetrofitService? {
if (INSTANCE == null) {
INSTANCE = RetrofitService()
}
return INSTANCE
}
}
init {
val mRetrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build()
profileApi = mRetrofit.create(ProfileAPI::class.java)
UserAPI = mRetrofit.create(UserAPI::class.java)
}
}
但是有一些东西告诉我这不是正确的方式,或者它可以做得更好。有什么可以在这里改进的吗?
更新!!!
根据评论和答案,我现在有了这个实现
object RetrofitService {
private const val BASE_URL = "https://test.api.com"
private fun retrofitService(): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build()
}
val profileApi: ProfileAPI by lazy {
retrofitService().create(ProfileAPI::class.java)
}
val userApi: UserAPI by lazy {
retrofitService().create(UserAPI::class.java)
}
}
然后我会像这样使用它
RetrofitService.profileApi
这样可以吗?
RetrofitService
可以是一个完整的对象。那么就没有必要有私有构造函数和初始化块了。 - Yevhen Danchenko