KhanStan99
KhanStan99

Reputation: 424

How to have multiple base URL in retrofit2 using Kotlin and Kodein structure

I have followed THIS tutorial for MVVM and Retrofit2 with Kodein structure/framework. I wanted to know, Using this same framework/structure how can i have multiple base URLs in a single App.

Below is the code of "MyApi" interface which have an interceptor class as parameter.

companion object {
    operator fun invoke(
        networkConnectionInterceptor: NetworkConnectionInterceptor
    ): MyApi {

        val okkHttpclient = OkHttpClient.Builder()
            .addInterceptor(networkConnectionInterceptor)
            .readTimeout(20, TimeUnit.SECONDS)
            .build()

        return Retrofit.Builder()
            .client(okkHttpclient)
            .baseUrl("http://my-base-url")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MyApi::class.java)
    }
}

And here is how Iam initializing MyApi interface in Application class:

    bind() from singleton { PreferenceProvider(instance()) }
    bind() from singleton { NetworkConnectionInterceptor(instance(), instance()) }
    bind() from singleton { MyApi(instance()) }

Here instance() in MyApi is obviously NetworkConnectionInterceptor.

I have seen a lot of examples on stackoverflow and medium but i didnt got any help.

Upvotes: 1

Views: 1869

Answers (1)

KhanStan99
KhanStan99

Reputation: 424

I think i found a work around to achive this. There are two solutions...

First Solution:

  • You can create a new interface for other microservice (base url) and use it just like the first one. Now there are some pros and cons for this.

Pros:

  • Both the interfaces will be independent of each other.
  • You can use either of the interface or both in same activity as you need.

Cons:

  • If there is another microservice poped up , you have to create one more interface for that. 😿
  • If you even have to 2 microservice and you have to run same application on development and qa server providing an option for testers and developers to switch between qa and dev servers at run time the you need to have 4 interfaces and 2 extra for production that means 6 interfaces, It will become very had to manage it.

Second Solution:

  • You can use @URL annotation provided by retrofit2. Now if you do this there will be no base_url, you have to pass the URL and microservice name in a common function which will return you a full URL based on what server users/testers are on (dev/qa or prod).

Pros:

  • No extra interfaces, Only one will work out.
  • Easy management of all the API calls because of the common function.

Cons:

  • You have to call the common funtion in @URL annotation in each and every API call.
  • I dont see any more. 😊

Upvotes: 1

Related Questions