代码之家  ›  专栏  ›  技术社区  ›  dotGitignore

当错误发生时,如何得到另一个可观察到的响应?

  •  0
  • dotGitignore  · 技术社区  · 6 年前

    我只想问,在遇到另一个可观测对象的错误后,是否有可能得到另一个可观测对象的响应?

    例如,我使用 combineLatest .

    val avatar: Observable<ResponseBody> = api().getAvatar()
    val attachment: Observable<ResponseBody> = api().getAttachment()
    
    val obs = Observables.combineLatest(avatar, attachment)
            .map { it ->
                if (it.first is Exception) {
                    Log.e(TAG, "getAvatar failed")
                } else {
                    updateAvatar()
                }
                if (it.second is Exception) {
                    Log.e(TAG, "getAttachment failed")
                } else {
                    updateAttachment()
                }
    
                if (it.first !is Exception && it.second !is Exception) {
                    Log.i(TAG, "success first=${it.first}, second=${it.second}")
                    updateAll()
                }
    
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .onErrorReturn { it }
            .subscribe()
    disposable.add(obs)
    

    如果附件出错,我只想得到头像响应,如果头像出错,我想得到附件响应。

    谢谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   karenkov_id    6 年前

    onErrorReturn() 方法。您可以使用空的ResponseBody来检测错误。最终代码

    val avatar: Observable<Optional<ResponseBody>> = api().getAvatar().onErrorReturn{ Optional.empty }
    val attachment: Observable<Optional<ResponseBody>> = api().getAttachment().onErrorReturn{ Optional.empty }
    
    val obs = Observables.combineLatest(avatar, attachment) {avatar, attachment -> 
            if (!avatar.isPresent()) {
                //logic
            }
            if (!attachment.isPresent()) {
                //logic
            }
        }.subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
         .onErrorReturn { it }
         .subscribe()
    

    如果在项目中使用Java7或更低版本,则可以编写自己的可选代码

    class Optional<T>(val value: T?) {
            companion object {
                fun <T> empty(): Optional<T> = Optional(null)
            }
    
            fun isPresent() = value != null
        }