提问人:Sam Sirvan 提问时间:10/23/2023 最后编辑:AbhimanyuSam Sirvan 更新时间:10/23/2023 访问量:16
如何在 Retrofit 中使用 Dynamic BaseUrl withhilt
how to use Dynamic BaseUrl in Retrofit withhilt
问:
我正在我的项目中使用刀柄进行改造。 因此,每次用户进来时,我都需要从用户那里获取 baseUrl,并使用该 baseUrl 调用 Web 服务。 我使用 Singleton 组件创建了我的 hilt Module 类,但是当应用程序运行时,baseUrl 不会更改。 我该如何解决?
这是我的 Hilt 模块:
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Singleton
@Provides
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(Prefs.AppSetting.BASE_URL)
.client(okHttpClient)
.addConverterFactory(
GsonConverterFactory.create()
)
.build()
}
}
这是我的常数:
object Prefs {
object AppSetting {
var BASE_URL: String = ""
}
}
最后,这是我的 compose 函数:
@Composable
fun ConnectionScreen(
navController: NavController,
viewModel: ServerMetaViewModel = hiltViewModel()
) {
val configuration = LocalConfiguration.current
val context = LocalContext.current
val uiState: State<ServerInfoState> by lazy {
viewModel.serverInfoUiState
}
val urlState = remember { mutableStateOf("") }
val onCheckServerClick: () -> Unit = {
Log.i("TAG_APP", "ConnectionScreen: ${urlState.value}")
Prefs.AppSetting.BASE_URL = ComposeUtils.toUrl(urlState.value)
viewModel.getServerInfo(urlState.value)
}
Column(
modifier = Modifier
.fillMaxWidth()
) {
UrlTextField(state = urlState, label = "Url")
FullWidthButton(
modifier = Modifier.align(Alignment.CenterHorizontally),
label = "Check Server",
enabled = ComposeUtils.isValidUrl(urlState.value) && !uiState.value.isLoading,
onClick = onCheckServerClick
)
if (uiState.value.isLoading) {
Spacer(modifier = Modifier.height(6.dp))
CircularProgressIndicator(
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
uiState.value.errors?.let {
it.forEach { error ->
Toast.makeText(context, error.description, Toast.LENGTH_SHORT).show()
}
}
uiState.value.data?.let {
Prefs.AppSetting.BASE_URL = urlState.value
navController.navigatePopUpTo(Destinations.Login.route)
}
答: 暂无答案
评论