WeatherRepository:
Код: Выделить всё
class WeatherRepository(
engine: HttpClientEngine,
private val locationClient: LocationClient
) {
...
suspend fun getCurrentWeather(): CurrentWeather {
val coordinates = locationClient.getCoordinates()
val requestUrl = "forecast?current_weather=true&latitude=${coordinates.lat}&longitude=${coordinates.lon}"
val response = httpClient.get(requestUrl)
println(response)
....
}
Код: Выделить всё
class HomeRepository(
private val weatherRepository: WeatherRepository
) {
suspend fun getCurrentWeather(): CurrentWeather {
return weatherRepository.getCurrentWeather()
}
}
Код: Выделить всё
class HomeViewModel(
private val homeRepository: HomeRepository,
scopeProvider: CoroutineScopeProvider
): ViewModel() {
...
private val scope = scopeProvider(viewModelScope)
private fun getCurrentWeather(refresh: Boolean) {
scope.launch {
try {
val weather = homeRepository.getCurrentWeather()
_uiState.update { it.copy(currentWeather = weather) }
} catch (e: Exception) {
...
}
}
}
Код: Выделить всё
class CoroutineScopeProvider(private val scope: CoroutineScope? = null,
private val dispatcher: CoroutineDispatcher) {
operator fun invoke(inputScope: CoroutineScope): CoroutineScope =
CoroutineScope((scope ?: inputScope).coroutineContext + dispatcher + SupervisorJob())
}
Код: Выделить всё
val dispatcher = StandardTestDispatcher()
val testScope = TestScope(dispatcher)
val coroutineScopeProvider = CoroutineScopeProvider(testScope, dispatcher = dispatcher)
viewModel = HomeViewModel(
scopeProvider = coroutineScopeProvider, ...)
Подробнее здесь: https://stackoverflow.com/questions/790 ... ck-compose
Мобильная версия