Danil
Danil

Reputation: 165

How i can use sealed class as return type in Retrofit2

My sealed class

sealed class TranslationResponse

data class Success(val code: Int, val text: List<String>) : TranslationResponse()
data class Error(val code: Int, val message: String) : TranslationResponse()

Retrofit2 request

@POST("/.....")
fun query(
    @Query("text") text: String,
    @Query("lang") lang: String,
    @Query("key") key: String = ""
): Observable<TranslationResponse>

when I call the following code

response.onErrorReturn { Error(code = 0, message = it.message ?: "error") }
        .subscribe {
            when (it) {
                is Success -> onTranslation(it.text[0])
                is Error -> Log.d([email protected], "translation error: ${it.code} ${it.message}")
            }
        }

I'm getting an exception

Caused by: java.lang.RuntimeException: Failed to invoke private ....TranslationResponse() with no args

P.S. If replace Observable<TranslationResponse> to Observable<Success> my code is works

Upvotes: 0

Views: 2568

Answers (1)

Samuel Eminet
Samuel Eminet

Reputation: 4737

I'm not sure you can achieve what you want, the closest for me would be something like this

@POST("/.....")
fun query(
    @Query("text") text: String,
    @Query("lang") lang: String,
    @Query("key") key: String = ""
): Observable<List<String>>

response.subscribe({ data -> handleResponse( Success(data)) },
                   { throwable -> handleResponse( Error (throwable.getMessage())})

fun handleResponse(response : TranslationResponse)
{
     when (response) {
                is Success -> ...
                is Error -> ...
            }
}

Upvotes: 1

Related Questions