12345678910111213141516171819202122232425262728 |
- package com.ted.weather.domain.datasource
- import com.ted.weather.data.db.ForecastDb
- import com.ted.weather.data.server.ForecastServer
- import com.ted.weather.domain.model.Forecast
- import com.ted.weather.domain.model.ForecastList
- import com.ted.weather.extensions.firstResult
- class ForecastProvider(val sources: List<ForecastDataSource> = ForecastProvider.SOURCES) {
- companion object {
- val DAY_IN_MILLIS = 1000 * 60 * 60 * 24
- val SOURCES by lazy { listOf(ForecastDb(), ForecastServer()) }
- }
- fun requestByZipCode(zipCode: Long, days: Int): ForecastList = requestToSources {
- val res = it.requestForecastByZipCode(zipCode, todayTimeSpan())
- if (res != null && res.size >= days) res else null
- }
- fun requestForecast(id: Long): Forecast = requestToSources { it.requestDayForecast(id) }
- private fun todayTimeSpan() = System.currentTimeMillis() / DAY_IN_MILLIS * DAY_IN_MILLIS
- private fun <T : Any> requestToSources(
- f: (ForecastDataSource) -> T?): T = sources.firstResult { f(it) }
- }
|