rxjs - 过滤后结合内部观察 [英] rxjs - combining inner observables after filtering
问题描述
我调用后端响应:
<预><代码>["https://some-url.com/someData1.json",https://some-url.com/someData2.json"]每个 JSON 可以具有以下架构:
<代码>{isValid":布尔值,数据":字符串}
我想获取包含所有数据的数组,其中 isValid 设置为 true
backend.get(url).管道(mergeMap((urls: []) =>urls.map((url: string) =>后端.get(网址).管道(过滤器(响应 => response.isValid),地图(响应 => 响应.数据)))),合并所有())
当两个 .json 都将isValid"设置为 true 时,我会得到包含两个数据的数组.但是当其中一个将isValid"设置为 false 时,observable 永远不会完成.
我可以使用 mergeAll 而不是 combineAll,但随后我收到的是单个数据流,而不是所有数据的集合.
有没有更好的方法过滤掉 observable?
正如您所说,内部 observable 永远不会发出,因为 filter
不会转发 发出的唯一值>backend.get
可观察的.在这种情况下,订阅该 observable 的运算符 - 在您的情况下 combineAll
- 也将永远不会收到任何值并且永远不会发出自己.
我要做的就是通过提供一个项目函数将过滤和映射移动到 combineAll
,如下所示:
backend.get(url).管道(mergeMap((urls: string[]) =>urls.map((url: string) => backend.get(url))),combineAll(响应 =>回应.filter(response => response.isValid).map(response => response.data)))
看看这是否适合你;)
I call backend that respond with:
[
"https://some-url.com/someData1.json",
"https://some-url.com/someData2.json"
]
Each JSON can have following schema:
{
"isValid": boolean,
"data": string
}
I want to get array with all data, that have isValid is set to true
backend.get(url)
.pipe(
mergeMap((urls: []) =>
urls.map((url: string) =>
backend.get(url)
.pipe(
filter(response => response.isValid),
map(response => response.data)
)
)
),
combineAll()
)
When both .json have "isValid" set to true, I get array with both data. But when one of them has "isValid" set to false observable never completes.
I could use mergeAll instead of combineAll, but then I receive stream of single data not collection of all data.
Is there any better way to filter out observable?
As you said, the inner observable never emits, because filter
does not forward the only value that is ever emitted by the backend.get
observable. In that case, the operator subscribing on that observable - in your case combineAll
- will also never receive any value and cannot ever emit itself.
What I would do is just move the filtering and mapping to combineAll
by providing a project function, like that:
backend.get(url)
.pipe(
mergeMap((urls: string[]) =>
urls.map((url: string) => backend.get(url))
),
combineAll(responses =>
responses
.filter(response => response.isValid)
.map(response => response.data)
)
)
See if that works for you ;)
这篇关于rxjs - 过滤后结合内部观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!