Skip to content

Instantly share code, notes, and snippets.

@uteke
Last active September 1, 2023 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uteke/8e6acc4bac806f301ea7d6a8c03048d7 to your computer and use it in GitHub Desktop.
Save uteke/8e6acc4bac806f301ea7d6a8c03048d7 to your computer and use it in GitHub Desktop.
UserListViewModel implementation with reducers
class UserListViewModel(
private val getUserListRepository: GetUserListRepository,
private val getUserContactRepository: GetUserContactRepository,
private val connectivityMonitor: ConnectivityMonitor,
private val reducers: Collection<Reducer<Mutation, ViewState>>,
private val tracker: Tracker,
private val logger: Logger,
): ViewModel() {
...
fun process(action: Action) {
when (action) {
is Action.Load -> load()
...
}
}
private fun load() {
viewModelScope.launch {
handleMutation(Mutation.ShowLoader)
when (val result = getProductsUseCase()) {
is Success -> {
tracker.trackEvent(CatalogFetched)
handleMutation(Mutation.ShowContent(users = result.users))
}
is Empty -> {
tracker.trackEvent(EmptyCatalogFetched)
logger.error(catalogResources.emptyCatalogMessage)
handleMutation(Mutation.ShowEmpty)
}
is Failure -> {
tracker.trackEvent(CatalogFetchFailed)
logger.error(catalogResources.failedCatalogMessage(result.errorType))
handleMutation(Mutation.ShowError(result.errorType))
}
}
}
}
...
private fun handleMutation(mutation: Mutation) {
reducers.asIterable()
.forEach { reducer ->
_viewStateFlow.update { currentState ->
reducer(mutation, currentState)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment