Created
December 5, 2021 20:49
-
-
Save MuratVarol/9a03dfb305f8657b6e5387764712b473 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import com.google.gson.JsonParseException | |
import com.sample.app.internal.util.Failure | |
import com.squareup.moshi.JsonDataException | |
import io.reactivex.Single | |
import io.reactivex.android.schedulers.AndroidSchedulers | |
/** | |
* Singleton class for handling API requests and responses | |
*/ | |
object ServiceRequestHandler { | |
/** | |
* Handles all requests and responses with success, errors and exceptions, | |
* fills data to Result data holder according to response type. | |
* *** Only Rx Single type supported. | |
*/ | |
fun <T> sendRequest(call: Single<T>): Single<Either<Failure, T>> { | |
return call | |
.observeOn(AndroidSchedulers.mainThread()) | |
.map<Either<Failure, T>> { | |
Either.Right(it) | |
} | |
.onErrorResumeNext { throwable: Throwable -> | |
Single.just( | |
Either.Left(toFailure(throwable)) | |
) | |
} | |
.doOnError { throwable: Throwable -> Either.Left(toFailure(throwable)) } | |
} | |
} | |
private fun toFailure(throwable: Throwable): Failure { | |
return when (throwable) { | |
is JsonParseException, is JsonDataException -> | |
Failure.ParsingDataError | |
else -> Failure.UnknownError(throwable.localizedMessage) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment