【问题标题】:RxJS Run Promise, then combineLatestRxJS 运行 Promise,然后 combineLatest
【发布时间】:2018-04-18 00:25:44
【问题描述】:

我为最近这么多明显的问题道歉,但我仍然很难掌握如何将所有内容链接在一起。

我有一个用户,他正在使用基于承诺的存储来存储他们不想看到的提要的名称。在社交订阅源小部件上,他们可以看到来自每个订阅源的最新文章,而这些文章还没有被过滤掉。

我想对提要的硬编码列表和他们想要隐藏的提要进行联合。要使用我提供的 API,我需要多次调用该服务以分别检索每个提要。

在建立联合之后,我希望按顺序组合实用程序 getFeed 方法产生的 observable。

这就是我希望用一些伪代码来做的事情。

/**
 * This gets the top items from all available social media sources.
 * @param limit {number} The number of items to get per source.
 * @returns {Observable<SocialItem[]} Returns a stream of SocialItem arrays.
 */
public getTopStories(limit: number = 1): Observable<SocialItem[]> {

    // Merge the list of available feeds with the ones the user wants to hide.
    const feedsToGet = this.storage.get('hiddenFeeds')
        .then(hiddenFeeds => _.union(FeedList, hiddenFeeds));

    // Let's use our function that retrieves the feeds and maps them into an Observable<SocialItem[]>.
    // We need to splice the list because only 'limit' amount of articles can come back from each feed, and the API cannot accommodate sending anything else than 25 items at a time. 
    // We need to do mergeMap in order to return a single array of SocialItem, instead of a 2D array.
    const feeds$ = feedsToGet.map(feed => this.getFeed(feed).map(res = res ? res.slice(0, limit) : []).mergeMap(val => val));

    // Let's combine them and return
    return Observable.combineLatest(feed$);
}

编辑:再一次,抱歉之前的代码稀疏。

【问题讨论】:

  • Observable.fromPromise... 之前的内容看起来也不起作用;你打算成为合并映射数组吗?更广泛地说,我会冒险猜测:您是否要在Promise&lt;Array&lt;Observable&lt;T&gt;&gt;&gt; 的结果上尝试combineLatest?
  • 我不确定我为什么要使用mergeMap。这是我能想出将所有数组扁平化为一个的唯一方法。
  • 我的错,我现在看到mergeMap automatically coerces Iterables to Observables。今天学到了新东西!

标签: javascript typescript promise rxjs


【解决方案1】:

您的示例的唯一问题是您在错误的时间范围内进行操作。 combineLatest 需要一个 Observable 数组,而不是 Observable 数组的 Future,提示您需要在 Promise 处理程序中 combineLatest。另一半是将Promise&lt;Observable&lt;SocialItem[]&gt;&gt; 强制转换为Observable&lt;SocialItem[]&gt; 的最后一步,这只是另一个mergeMap。总而言之:

public getTopStories(limit: number = 1): Observable<SocialItem[]> {
    // Merge the list of available feeds with the ones the user wants to hide.
    const feeds_future = this.storage.get('hiddenFeeds')
        .then(hiddenFeeds => Observable.combineLatest(_.map(
          _.union(FeedList, hiddenFeeds),
          feed => this.getFeed(feed).mergeMap(res => res ? res.slice(0, limit) : [])
        ))); // Promise<Observable<SocialItem[]>>

    return Observable.fromPromise(feeds) // Observable<Observable<SocialItem[]>>
                     .mergeMap(v => v); // finally, Observable<SocialItem[]>
}

附: mergeMap 的投影功能意味着您可以在合并时将值映射到 Observables,而不是分别映射和合并它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多