-
Notifications
You must be signed in to change notification settings - Fork 11
/
How to use Multiple BASE_URLs with Retrofit using Dagger Hilt2 Dependency Injection?
84 lines (61 loc) · 1.89 KB
/
How to use Multiple BASE_URLs with Retrofit using Dagger Hilt2 Dependency Injection?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
## Problem
How to use Multiple BASE_URLs with Retrofit using Dagger Hilt2 Dependency Injection.
## How you fix it
You can achieve by using Qualifier. Let's see an example:
## Solution
1. Create a kotlin class e.g. Qualifiers.kt and defined Qualifier you need
```
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class Auth
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class Setting
```
2. Create module class e.g. NetworkModule.kt
```
@Provides
@Singleton
@Auth //This will differentiate retrofit object
fun retrofitAuth(
client: OkHttpClient,
gsonConverterFactory: GsonConverterFactory
): Retrofit =
Retrofit.Builder()
.client(client)
.addConverterFactory(gsonConverterFactory)
.baseUrl("https://someauth.baseurl.com").build()
@Provides
@Singleton
@Setting //This will differentiate retrofit object
fun retrofitSetting(
client: OkHttpClient,
gsonConverterFactory: GsonConverterFactory
): Retrofit =
Retrofit.Builder()
.client(client)
.addConverterFactory(gsonConverterFactory)
.baseUrl("https://someSetting.baseurl.com").build()
//Build Api services with respect to qualifiers
@Provides
@Singleton
fun authApiService(@Auth retrofit: Retrofit): AuthApiService = retrofit.create(AuthApiService::class.java)
@Provides
@Singleton
fun settingApiService(@Setting retrofit: Retrofit): SettingApiService = retrofit.create(SettingApiService::class.java)
```
3. Create separate Api Service interfaces e.g. AuthApiService and SettingApiService
```
interface AuthApiService {
@FormUrlEncoded
@POST("login/v2")
fun login(@FieldMap params: HashMap<String, Any>): Response<LoginResponse>
}
interface SettingApiService {
@GET("settings")
fun settings(): Response<SettingsResponse>
@GET("faqs")
fun getFAQs(): Response<FAQsResponse>
}
```