android 安卓Kotlin+ Retrofit + Hlt + MVVM change dynamic url runtime

disho6za  于 2023-06-04  发布在  Android
关注(0)|答案(2)|浏览(155)
@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {

    @Singleton
    @Provides
    fun providesRetrofit(okHttpClient: OkHttpClient): Retrofit{
        //val contentType = "application/json".toMediaType()

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        val httpBuilder = OkHttpClient.Builder()
        httpBuilder
            //.dispatcher(dispatcher)
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(interceptor)  /// show all JSON in logCat
        val mClient = httpBuilder.build()

        return Retrofit.Builder()
            //.addConverterFactory(Json.asConverterFactory(contentType))
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .client(mClient)
            .build()
    }

    @Provides
    fun provideHTTPLoggingInterceptor(): HttpLoggingInterceptor {
        val interceptor = HttpLoggingInterceptor()
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        return interceptor
    }

    @Provides
    fun provideOkHttpClient(loggingInterceptor: HttpLoggingInterceptor
    ): OkHttpClient {
        return OkHttpClient.Builder()
            .callTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60,TimeUnit.SECONDS)
            .writeTimeout(60,TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .build()
    }

    @Singleton
    @Provides
    fun providesSalesAPI(retrofit: Retrofit): SalesApi {
        return retrofit.create(SalesApi::class.java)
    }
}

如何在单击任何按钮时更改BASE_URL?我使用MVVM存储库模式,无法更改URL运行时。请帮助我在上面的例子中有什么要改变的。注意:如果我重新启动应用程序的URL将更改,但我想改变没有应用程序重新启动的URL

qxgroojn

qxgroojn1#

我不确定这是否是最好的解决方案,但您可以使用两个BASE_URL创建两个Retrofit示例:

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class RetrofitOne

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class RetrofitTwo

@Provides
@Singleton
@RetrofitOne
fun providesRetrofit(okHttpClient: OkHttpClient):
    return Retrofit.Builder()
            .baseUrl(BASE_URL_1)
            ...

@Provides
@Singleton
@RetrofitTwo
fun providesRetrofit(okHttpClient: OkHttpClient):
    return Retrofit.Builder()
            .baseUrl(BASE_URL_2)
            ...

@Provides
@Singleton
fun providesSalesAPI(@RetrofitOne retrofit: Retrofit): SalesApi {
    return retrofit.create(SalesApi::class.java)
}

@Provides
@Singleton
fun providesAnotherSalesAPI(@RetrofitTwo retrofit: Retrofit): SalesApi {
    return retrofit.create(SalesApi::class.java)
}

相关问题