ForecastProvider.kt 1.0 KB

12345678910111213141516171819202122232425262728
  1. package com.ted.weather.domain.datasource
  2. import com.ted.weather.data.db.ForecastDb
  3. import com.ted.weather.data.server.ForecastServer
  4. import com.ted.weather.domain.model.Forecast
  5. import com.ted.weather.domain.model.ForecastList
  6. import com.ted.weather.extensions.firstResult
  7. class ForecastProvider(val sources: List<ForecastDataSource> = ForecastProvider.SOURCES) {
  8. companion object {
  9. val DAY_IN_MILLIS = 1000 * 60 * 60 * 24
  10. val SOURCES by lazy { listOf(ForecastDb(), ForecastServer()) }
  11. }
  12. fun requestByZipCode(zipCode: Long, days: Int): ForecastList = requestToSources {
  13. val res = it.requestForecastByZipCode(zipCode, todayTimeSpan())
  14. if (res != null && res.size >= days) res else null
  15. }
  16. fun requestForecast(id: Long): Forecast = requestToSources { it.requestDayForecast(id) }
  17. private fun todayTimeSpan() = System.currentTimeMillis() / DAY_IN_MILLIS * DAY_IN_MILLIS
  18. private fun <T : Any> requestToSources(
  19. f: (ForecastDataSource) -> T?): T = sources.firstResult { f(it) }
  20. }