Skip to content

Commit

Permalink
Move loading state change to BaseViewModel, set it whenever UseCase i…
Browse files Browse the repository at this point in the history
…s invoked
  • Loading branch information
LukaKordic committed Sep 4, 2019
1 parent d6e8eca commit 698e5c5
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ abstract class BaseViewModel<T : Any, E> : ViewModel(), KoinComponent {
get() = _viewEffects

protected fun executeUseCase(action: suspend () -> Unit, noInternetAction: () -> Unit) {
_viewState.value = Loading()
if (connectivity.hasNetworkAccess()) {
launch { action() }
} else {
Expand All @@ -33,6 +34,7 @@ abstract class BaseViewModel<T : Any, E> : ViewModel(), KoinComponent {
}

protected fun executeUseCase(action: suspend () -> Unit) {
_viewState.value = Loading()
launch { action() }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,9 @@ import com.example.domain.model.onSuccess

class WeatherViewModel(private val getWeather: GetWeatherUseCase) : BaseViewModel<WeatherInfo, WeatherViewEffects>() {

fun getWeatherForLocation(location: String = DEFAULT_CITY_NAME) {
executeUseCase {
_viewState.value = Loading()
getWeather(location)
.onSuccess { _viewState.value = Success(it) }
.onFailure { _viewState.value = Error(it.throwable) }
}
}
fun getWeatherForLocation(location: String = DEFAULT_CITY_NAME) = executeUseCase {
getWeather(location)
.onSuccess { _viewState.value = Success(it) }
.onFailure { _viewState.value = Error(it.throwable) }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ abstract class BaseRepository<T : Any, R : DomainMapper<T>> : KoinComponent {
private val connectivity: Connectivity by inject()
private val contextProvider: CoroutineContextProvider by inject()

/**
* Use this if you need to cache data after fetching it from the api, or retrieve something from cache
*/
protected suspend fun fetchData(
apiDataProvider: suspend () -> Result<T>,
dbDataProvider: suspend () -> R
Expand All @@ -33,6 +36,9 @@ abstract class BaseRepository<T : Any, R : DomainMapper<T>> : KoinComponent {
}
}

/**
* Use this when communicating only with the api service
*/
protected suspend fun fetchData(dataProvider: () -> Result<T>): Result<T> {
return if (connectivity.hasNetworkAccess()) {
withContext(contextProvider.io) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class WeatherRepositoryImpl(private val weatherApi: WeatherApi,
fetchFromCacheAction = { weatherDao.getWeatherInfoForCity(location) },
cacheAction = { weatherDao.saveWeatherInfo(it) })
},
dbDataProvider = { weatherDao.getWeatherInfoForCity(location) })
dbDataProvider = { weatherDao.getWeatherInfoForCity(location) }
)
}
}

0 comments on commit 698e5c5

Please sign in to comment.