RxJava:吞没错误后,上游永远不会完成 [英] RxJava: upstream never completes when error is swallowed

查看:96
本文介绍了RxJava:吞没错误后,上游永远不会完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RxJava遍历文件列表,进行网络调用以上传每个文件,然后将成功上传的文件收集到列表中,并在成功后将这些文件持久保存在订阅服务器中.

I'm using RxJava to iterate over a list of files, making a network call to upload each file, then collect the files that were successfully uploaded in a list and persist those files in the subscriber on success.

此代码有效,但发生错误时除外.行为应该是它记录错误并继续执行,除非发生错误,否则订户的onSuccess lambda永远不会被调用.

This code works, except for when an error occurs. The behavior should be that it logs the error and continues, which it does, except when an error occurs the subscriber's onSuccess lambda never gets called.

观察者是否期望发出与原始可迭代元素相同数量的元素?迭代完所有项目后,如何跳过错误并完成错误?除了Single.never()之外,还有没有其他东西可以将错误转发给下游?

Is the observer expecting the same number of elements to be emitted as are in the original iterable? How can I skip the errors and have it complete once all items have been iterated over? Is there something other than Single.never() that will accomplish not forwarding the error to the downstream?

queryFiles()?.let { files ->
    Observable.fromIterable(files)
            .flatMapSingle { file ->
                uploadFile(file)
                        .onErrorResumeNext { error ->
                            log(error)
                            Single.never() // if this is returned onSuccess is never called
                        }
                        .map { response ->
                            file.id = response.id
                            file
                        }
            }
            .toList()
            .subscribe( { uploadedFiles ->
                persist(uploadedFiles) // if error occurs above, this is never called
            }, { error ->
                log(error)
            })
}

推荐答案

您的问题是Single只能产生两个值,即成功结果或失败结果.通过先将故障转换为Maybe,然后使用基本上相同的代码来处理故障和成功,可以将故障转变为忽略"状态.

Your problem is that Single can only result in two values, a successful result or a failure. Turning the failure in an 'ignored' state can be done by first converting it to a Maybe and then using essentially the same code to handle failure and success.

Maybe.onErrorResumeNext将导致0或1个结果,而Maybe.map仅在具有值的情况下才执行,可以如您所描述的那样准确地解决问题.

Maybe.onErrorResumeNext with a return value of Maybe.empty() would result in 0 or 1 results while Maybe.map only executes if it has a value, accurately handling the problem as you've described it.

自适应代码:

        .flatMapMaybe { file ->
            uploadFile(file).toMaybe()
                    .onErrorResumeNext { error: Throwable ->
                        log(error)
                        Maybe.empty()
                    }
                    .map { response ->
                        file.id = response.id
                        file
                    }
        }

这篇关于RxJava:吞没错误后,上游永远不会完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆