Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- abstract class BaseRepository<T : WithFailureMessage<T>>(private val exceptionMapper: ExceptionMapper) {
- suspend fun doRequest(fail: T,block: suspend () -> T) : T {
- return try {
- block.invoke()
- } catch (e: java.lang.Exception) {
- fail.withMessage(exceptionMapper.map(e))
- }
- }
- }
- // Example usage
- interface AuthRepository {
- suspend fun login(auth: Auth) : DataAuth
- suspend fun register(auth: Auth) : DataAuth
- class Base(
- private val authCloudDataSource: AuthCloudDataSource,
- private val mapper: CloudToDataAuthMapper,
- private val authSharedPreferences: AuthSharedPreferences,
- exceptionMapper: ExceptionMapper
- ) : AuthRepository, BaseRepository<DataAuth>(exceptionMapper) {
- override suspend fun login(auth: Auth): DataAuth
- = doRequest(DataAuth.Empty) { authCloudDataSource.login(auth).map(mapper) }
- override suspend fun register(auth: Auth): DataAuth {
- val result = doRequest(DataAuth.Empty) { authCloudDataSource.register(auth).map(mapper) }
- result.save(authSharedPreferences)
- return result
- }
- }
- interface WithFailureMessage<T> {
- fun withMessage(message: String) : T
- }
- sealed class DataAuth : WithFailureMessage<DataAuth> {
- data class Failure(
- private val message: String
- ) : DataAuth() {
- override fun <T> map(mapper: Abstract.AuthMapper<T>): T
- = mapper.map(message)
- }
- object Empty : DataAuth() {
- override fun withMessage(message: String): DataAuth = Failure(message)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement