我的密封课
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请求
@POST("/.....")
fun query(
@Query("text") text: String,
@Query("lang") lang: String,
@Query("key") key: String = ""
): Observable<TranslationResponse>
当我调用以下代码时
response.onErrorReturn { Error(code = 0, message = it.message ?: "error") }
.subscribe {
when (it) {
is Success -> onTranslation(it.text[0])
is Error -> Log.d(this@CustomTextWatcher.javaClass.name, "translation error: ${it.code} ${it.message}")
}
}
我得到了例外
引起:java.lang.RuntimeException:无法调用private ....没有args的TranslationResponse()
P.S。如果将Observable<TranslationResponse>
替换为Observable<Success>
我的代码有效
答案 0 :(得分:1)
我不确定你能达到你想要的效果,对我来说最接近的就是这样的
@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 -> ...
}
}