Java 8
io.reactivex:rxjava:1.3.6
kotlin 1.2.21
我试图使用Single传递doOnSuccess中的参数。
但是,我收到一个错误,我似乎无法解决。
class TranslateInteractor(val repository: Respository) {
fun requestNetworkTranslated(message: String): Completable {
return repository.fetchTranslation(message)
.doOnSuccess { handleTranslationResponse(message, it) }.toCompletable()
}
private fun handleTranslationResponse(message, String, translatedResponse: TranslatedResponse) {
saveTranslation(
"",
translatedResponse.content,
translatedResponse.translationEngine)
}
private fun saveTranslation(message: String, content: String, engine: String) {
/* Save to local storage */
}
}
错误发生在.doOnSuccess中。因为我想将消息传递给handleTranslationResponse。
Type mismatch: inferred type is String but TranslatedResponse was expected
如何将消息以及从TranslatedResponse获取的内容传递回HandleTranslationResponse?
存储库是一个返回单个的java类:
public class Respository {
private NetworkAPI networkAPI;
public Single<TranslatedResponse> fetchTranslation(final String message) {
return networkAPI.fetchTranslation(new TranslateRequest(message));
}
}
我在Kotlin的数据类是:
data class TranslatedResponse(
val content: String,
val translationEngine: String)
并要求
data class TranslateRequest(val message: String)
对于networkAPI,我在java片段中有以下内容:
public interface NetworkAPI {
Single<TranslatedResponse> fetchTranslation(TranslateRequest request);
}
非常感谢任何建议,
你不能这样做的原因是因为doOnSucess
只接受一个参数,这是Repository
返回的任何参数。
您需要以某种方式将原始消息添加到Repository
返回的响应中。有几种选择(例如使用Pair
或新的data class
)
一个例子:
data class Translation(
val originalMessage: String,
val translatedMessage: TranslationResponse
)
现在你的Repository
成为:
public class Respository {
private NetworkAPI networkAPI;
public Single<TranslatedResponse> fetchTranslation(final String message) {
return new Translation(
message,
networkAPI.fetchTranslation(new TranslateRequest(message)
);
}
}
最后,handleTranslationResponse
现在采用Translation
代替,这使你的交互器看起来像:
class TranslateInteractor(val repository: Respository) {
fun requestNetworkTranslated(message: String): Completable {
return repository.fetchTranslation(message)
.doOnSuccess { handleTranslationResponse(it) }.toCompletable()
}
private fun handleTranslationResponse(translation: Translation) {
saveTranslation(
translation.originalMessage,
translation.translatedMessage.content,
translation.translatedMessage.translationEngine)
}
private fun saveTranslation(message: String, content: String, engine: String) {
// do whatever you want!
}
}