Untitled
unknown
kotlin
a month ago
3.6 kB
8
Indexable
Never
Code binding.layoutChangeCountrySelect.confirmCountry.setOnClickListener { binding.imgSelectedCountry.setImageResource( if (binding.layoutChangeCountrySelect.countrySelectionUk.alpha == 1f) R.drawable.icon_uk else R.drawable.icon_usa ) if (binding.layoutChangeCountrySelect.countrySelectionUk.alpha == 1f) { landingViewModel.saveCountryCode("uk") } else { landingViewModel.saveCountryCode("usa") } binding.layoutChangeCountrySelect.viewLocationLayout.visibility = View.GONE } fun saveCountryCode(countryCode: String) = viewModelScope.launch { schoolStoreRepository.saveCountryCode(countryCode) } suspend fun saveCountryCode(countryCode: String) { schoolDataStore.edit { preferences -> preferences[PreferenceKeys.countryCode] = countryCode } } Another Activity lifecycleScope.launch(Dispatchers.IO) { schoolViewModel.countryCodeFlow.collect{countryCode -> when(countryCode){ "uk" -> { if (BuildConfig.BUILD_TYPE == "debug"){ schoolViewModel.updateBaseURL(SCH_BASE_UK_DEBUG) }else { schoolViewModel.updateBaseURL(SCH_BASE_UK_PROD) } } "usa" -> { if (BuildConfig.BUILD_TYPE == "debug"){ schoolViewModel.updateBaseURL(SCH_BASE_USA_DEBUG) }else { schoolViewModel.updateBaseURL(SCH_BASE_USA_PROD) } } } } } API Setup fun updateBaseURL(appUrl: String){ apiConfig.setBaseUrl(appUrl) } Change Base URL class ApiConfig @Inject constructor() { private val _baseUrl = MutableStateFlow(Constant.SCH_BASE_UK_DEBUG) val baseUrl: StateFlow<String> get() = _baseUrl fun setBaseUrl(newUrl: String) { _baseUrl.value = newUrl } fun getBaseUrl(): String { return _baseUrl.value } } Network Module for setting Retrofit @Module @InstallIn(SingletonComponent::class) class NetworkModule { @Singleton @Provides fun provideHttpClient(): OkHttpClient { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY return OkHttpClient.Builder() .readTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS) .addNetworkInterceptor(interceptor) .build() } @Singleton @Provides fun provideConverterFactory(): GsonConverterFactory { val gson = GsonBuilder().setLenient().create() return GsonConverterFactory.create(gson) } @Provides fun provideRetrofitInstance( okHttpClient: OkHttpClient, gsonConverterFactory: GsonConverterFactory, apiConfig: ApiConfig ): Retrofit { return Retrofit.Builder() .baseUrl(apiConfig.baseUrl.value) // Use dynamic base URL here .addConverterFactory(gsonConverterFactory) .client(okHttpClient) .build() } @Provides fun provideApiService(retrofit: Retrofit): SchoolApi { return retrofit.create(SchoolApi::class.java) } }
Leave a Comment