Created
May 15, 2021 12:33
-
-
Save ChristopherME/65670e472db86383cdbe632064dd0415 to your computer and use it in GitHub Desktop.
Safe retrofit call extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This would be your remote data source implementation. Only the [ActorsRemoteDataSource] is injected in your repository implementation. | |
*/ | |
internal class ActorsRemoteDataSourceImpl( | |
private val middlewareProvider: MiddlewareProvider, | |
private val ioDispatcher: CoroutineDispatcher, | |
private val errorAdapter: JsonAdapter<ResponseError>, | |
private val actorsService: ActorsService | |
) : ActorsRemoteDataSource { | |
override suspend fun getActors(): Either<Failure, List<ActorsResponse>> { | |
return call( | |
middleWares = middlewareProvider.getAll(), | |
ioDispatcher = ioDispatcher, | |
adapter = errorAdapter, | |
retrofitCall = { | |
actorsService.getActors( | |
language = "en-US", | |
page = 1 | |
) | |
} | |
).let { response -> response.mapSuccess { responseItems -> responseItems.results } } | |
} | |
} | |
/* | |
* This is how your repository implementation would look like. | |
*/ | |
internal class ActorsRepositoryImpl( | |
private val remoteDataSource: ActorsRemoteDataSource, | |
private val mapper: ActorsMapper | |
) : ActorsRepository { | |
override suspend fun getActors(): Either<Failure, List<Actor>> { | |
return remoteDataSource.getActors() | |
.coMapSuccess { remoteItems -> | |
mapper.mapRemoteActorsToDomain(remoteItems) | |
} | |
} | |
} | |
/* | |
* Finally your viewmodel/presenter would look like this | |
*/ | |
class ActorsListViewModel( | |
private val actorsRepository: ActorsRepository, | |
private val mapper: ActorsMapper | |
) : ViewModel() { | |
private val _uiState = MutableStateFlow(ActorsListUiState()) | |
val uiState = _uiState.asStateFlow() | |
init { | |
getActors() | |
} | |
private fun getActors() { | |
viewModelScope.launch { | |
_uiState.value = uiState.value.copy(isLoading = true) | |
actorsRepository | |
.getActors() | |
.coMapSuccess { domainActors -> mapper.mapDomainActorsToUi(domainActors) } | |
.either(::handleGetActorsFailure, ::handleGetActorsSuccess) | |
} | |
} | |
private fun handleGetActorsSuccess(actors: List<ActorUi>) { | |
_uiState.value = uiState.value.copy( | |
isLoading = false, | |
actors = actors, | |
error = null | |
) | |
} | |
private fun handleGetActorsFailure(failure: Failure) { | |
_uiState.value = uiState.value.copy( | |
isLoading = false, | |
error = failure.toOneTimeEvent() | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment