科特林+ Dagger2 +改造+命名

时间:2018-03-02 17:13:43

标签: android kotlin retrofit named-scope

我尝试使用Kotlin和Dagger 2构建指向不同基本URL的两个不同的Retrofit对象,如下所示 -

object Constant {
const val BASE_URL_1 = "https://baseurl1.xyz/"
const val BASE_URL_2 = "https://baseurl2.xyz/"
}


@Provides
@ApplicationScope
@Named(BASE_URL_1)
internal fun retrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit {
    return Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(BASE_URL_1)
            .client(okHttpClient)
            .build()
}

@Provides
@ApplicationScope
@Named(BASE_URL_2)
internal fun retrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit {
    return Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(BASE_URL_2)
            .client(okHttpClient)
            .build()
}

然后我创建了改造界面 -

@Provides
@ApplicationScope
fun api_1(@Named(BASE_URL_1) retrofit: Retrofit): Api_1 {
    return retrofit.create<Api_1>(Api_1::class.java)
}

@Provides
@ApplicationScope
fun api_2(@Named(BASE_URL_2) retrofit: Retrofit): Api_2 {
    return retrofit.create<Api_2>(Api_2::class.java)
}

Stacktrace - https://gist.github.com/tejasna/18a50cc803116adb48300b7a6d6c98b2

截图 compiler error -

但是我得到了一个冲突的重载编译器异常。

请咨询?提前谢谢。

0 个答案:

没有答案