Map Retrofit RxJava Result into sealed class Success and failure


I am using retrofit with RXJava to call my APIs, i am trying to map my call result into sealed class success and failure parts,

I did the mapping part but I am always getting this error java.lang.RuntimeException: Failed to invoke private Result() with no args

Here is my code:

Retrofit interface

fun UpdateProfile(@Body testBody: TestBody): Single<Result<TestResult>>

Result Sealed Class

sealed class Result<T> {
data class Success<T>(val value: T) : Result<T>()
data class Failure<T>(val throwable: Throwable) : Result<T>()}

Call and Mapping

        .onErrorReturn {
        .map {
            when (it) {
                is  Result.Failure ->  Failure(it.throwable)
                is  Success -> Success(it.value)

anyone can help with that? why I am getting this error?


The problem is your retrofit interface return type: Single<Result<TestResult>>. Retrofit has no way of knowing that your Result is a polymorphic type, it’ll just try to instantiate whichever class you specify. In this case Result can’t be instantiated directly because it is sealed.

You need to either use a non-polymorphic return type, or configure retrofit accordingly.

Answered By – F43nd1r

Leave a Comment