i want to provide a single gson instance, so i provide it in my NetworkModule, when i create retrofit api, gson is non null, but when i use gson instance in retrofit class, it is null..
@Module
class NetworkModule {
@Provides
@Singleton
fun provideGson(): Gson {
return Gson()
}
@Provides
@Singleton
fun provideMyEnterpriseApi(gson: Gson): MyEnterpriseApi {
//HERE GSON IS NOT NULL
return RetrofitMyEnterpriseApi(BuildConfig.API_MYENTERPRISE_URL,
BuildConfig.API_MYENTERPRISE_CONNECTION_TIMEOUT,
BuildConfig.API_MYENTERPRISE_READ_TIMEOUT,
gson)
}
}
My retrofit api class :
class RetrofitMyEnterpriseApi(baseUrl: String, connectTimeout: Long, readTimeout: Long, private val gson: Gson)
: RetrofitApi<RetrofitMyEnterpriseCalls>(baseUrl, connectTimeout, readTimeout, RetrofitMyEnterpriseCalls::class.java) {
override fun buildRetrofit(baseUrl: String, connectTimeout: Long, readTimeout: Long): Retrofit {
val builder = Retrofit.Builder()
builder.baseUrl(baseUrl)
builder.client(buildClient(connectTimeout, readTimeout))
builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
builder.addConverterFactory(GsonConverterFactory.create(gson))
return builder.build()
}
private fun buildClient(connectTimeout: Long, readTimeout: Long): OkHttpClient {
//HERE GSON IS NULL
return OkHttpClient.Builder()
.addInterceptor(OAuth2Interceptor(gson, this))
.addInterceptor(LoggingInterceptor.newInstance())
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
.build()
}
}
RetrofitApi class:
abstract class RetrofitApi<C>
(baseUrl: String, connectTimeout: Long, readTimeout: Long, callsClass: Class<C>) {
protected val calls: C
init {
val retrofit = buildRetrofit(baseUrl, connectTimeout, readTimeout)
calls = retrofit.create(callsClass)
}
protected abstract fun buildRetrofit(baseUrl: String, connectTimeout: Long, readTimeout: Long): Retrofit
}
So, when i provide it's not null, but when i use it in buildClient method is null, i can't see why, i miss something in Kotlin maybe.