Hi i have an issue with Kotlin not allowing overri...
# android
t
Hi i have an issue with Kotlin not allowing overriding functions to specify default values for its parameters my android application is using retrofit for api calls this means i have to specify network calls in an interface as follows:-
@POST(value = "MyEndpoint")
suspend fun myApiCall(@HeaderMap headers: Map<String, String>, @Body request: LoginRequest): Either<CallError, LoginResponse>
I then have to implement this interface as a service as follows:-
class MyApiService @Inject constructor(retrofit: Retrofit) : MyApi {
private val service: MyApi = retrofit.create(MyApi::class.java)
override suspend fun myApiCall(headers: Map<String, String>, request: LoginRequest): Either<CallError, LoginResponse> =
service.myApiCall(headers, request)
}
i then "wrap" this service in a repository class so that i can encapsulate database and data encryption functions to ensure the repository implements all network calls it also implements the retrofit api interface implementing the retrofit api means i am garuanteed to implement all network calls, and not miss any however i would like to set the headers within the repository so that client calls to the repository do not have do deal with creating and pass the header map how can i get the "best of both worlds"? e.g. be sure my repository is implementing all network calls specified in the retrofit api AND have my repository expose functions that do not require clients to pass a header map?
z
You can build an interceptor that uses your repo to add headers to each API call and then attach that to your retrofit client
t
@Zun i thought of that, it is a nice idea, however there is an issue in my particular use case.... i need to read a row from my local database to retrieve the header content, and i employ hilt for DI with my okHttpClient being a singleton, which all results in the okHttpClient being @Provided when the database table is empty 😞
z
I have no idea what you’re saying. Why is your database table empty? Are you querying your database once or every time you perform a HTTP request?
t
because when my user is signing in the first network call i make is to retrieve the auth token which means that network call does not expect an authorization header once the user is signed in ok i have the auth token in my local database, all subsequent api calls need the auth header adding, however hilt will not provide a new okHttpClient as its a singleton i do not want to have a new okHttpClient instantiated every time i make a network call for all subsequent api calls my database is populated however the okHttpClient has already been created without the auth header
z
You don’t have to create a new client. Inside your interceptor, for each API call you can fetch the required data from your tables
https://square.github.io/okhttp/features/interceptors/. Subclass the interceptor, inject your repo and inside the intercept method just get the data from database