Skip to content

Instantly share code, notes, and snippets.

View LukaKordic's full-sized avatar

Luka Kordić LukaKordic

View GitHub Profile
class GetWeatherUseCaseImpl(private val weatherRepository: WeatherRepository) : GetWeatherUseCase {
override suspend operator fun invoke(location: String) = weatherRepository.getWeatherForLocation(location)
}
sealed class Result<out T : Any>
data class Success<out T : Any>(val data: T) : Result<T>()
data class Failure(val httpError: HttpError) : Result<Nothing>()
class HttpError(val throwable: Throwable, val errorCode: Int = 0)
inline fun <T : Any> Result<T>.onSuccess(action: (T) -> Unit): Result<T> {
if (this is Success) action(data)
return this
}
@Dao
interface WeatherDao {
@Transaction
suspend fun updateWeatherAndReturn(weather: WeatherEntity): WeatherEntity {
saveWeatherInfo(weather)
return getWeatherInfoForCity(weather.name ?: "")
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
interface WeatherApi {
@GET("weather")
suspend fun getWeatherForLocation(@Query("q") location: String, @Query("appid") apiKey: String = API_KEY): Response<WeatherInfoResponse>
}
class WeatherRepositoryImpl(private val weatherApi: WeatherApi,
private val weatherDao: WeatherDao) : BaseRepository<WeatherInfo, WeatherEntity>(), WeatherRepository {
override suspend fun getWeatherForLocation(location: String): Result<WeatherInfo> {
return fetchData(
apiDataProvider = {
weatherApi.getWeatherForLocation(location).getData(
fetchFromCacheAction = { weatherDao.getWeatherInfoForCity(location) },
cacheAction = { weatherDao.saveWeatherInfo(it) })
},
dbDataProvider = { weatherDao.getWeatherInfoForCity(location) }