rxjava使用Single在doOnSuccess中传递参数

时间:2018-02-27 14:35:52

标签: java kotlin rx-java

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);
}

非常感谢任何建议,

1 个答案:

答案 0 :(得分:2)

您无法做到这一点的原因是因为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!
    }
}