#android #retrofit
#Android #модернизация
Вопрос:
Я хотел обновить это private val api
в функции getMenu, но я не знаю как. Моя идея заключалась в том, чтобы изменить базовый URL api в зависимости от взаимодействия пользователя со счетчиком.
@Singleton
class WwMenuRepository @Inject constructor(private val api: ApiInterface,
private val gson: Gson,
private val applicationPreferences: ApplicationPreferences,
@Named("is_stage") private val isStage: Boolean,
cachedValueFactory: CachedValueFactory) : CacheableRepository(cachedValueFactory), MenuRepository {
override fun getMenu(isLoggedIn: Boolean): Single<List<MenuEntry>> {
val cachedMenuCall = cachedSingle(methodCacheId = "getMenu", param = isLoggedIn.toString(), singleToCache = api.getMenu().map { mapMenu(it) })
return if (isLoggedIn) {
cachedMenuCall
} else {
cachedMenuCall.onErrorReturn {
menuFailover()
}
}
}
override fun refreshMenu(isLoggedIn: Boolean): Single<List<MenuEntry>> {
clearCache()
return getMenu(isLoggedIn = isLoggedIn)
}
private fun menuFailover(): List<MenuEntry> {
val country = applicationPreferences.getSelectedCountry() ?: Country.BRAZIL
val filename = "menu_$country.json"
val bufferedReader = javaClass.classLoader?.getResourceAsStream(filename)?.bufferedReader()
val inputString = bufferedReader.use { it?.readText() }
return mapMenu(gson.fromJson<MenuResponse>(inputString, MenuResponse::class.java))
}
private fun mapMenu(menuResponse: MenuResponse): List<MenuEntry> {
val menu = menuResponse.data.mapNotNull { it.map() }
return if (isStage) {
menu.plus(MenuEntry("Change Shop", MenuEntryType.APPLINK, "changeShop", null))
} else menu
}
}
Ответ №1:
Я думаю, что вам следует написать такую оболочку:
//Base inerface for all apis
interface IApiService {
val anyApi: IAnyApi
fun setBaseUrl(url: String)
}
class ApiService: IApiService {
lateinit var _anyApi: IAnyApi
override val anyApi: IAnyApi
get() = _anyApi
init {
//it must initialize _apiService for avoid problems
setBaseUrl(DEFAULT_URL)
}
fun setBaseUrl(url: String) {
//initialize retrofit and recreate anyApi
...
}
}
Затем вы можете ввести IApiService и вызвать такие методы, как
apiService.anyApi.getAnything()