首页 > 解决方案 > 使用 switchMap 发出一个热布尔可观察对象?

问题描述

尝试创建isEmpty:Observable<boolean>一个Observable<boolean>使用switchMap. 这是我到目前为止所拥有的:

  /**
   * Notifies observers when the store is empty.
   */
  protected notifyOnEmpty = new ReplaySubject<E[]>(1);

  /**
   * Check whether the store is empty.
   * 
   * @return A hot {@link Observable<boolean>} that indicates whether the store is empty.
   * 
   * @example
     <pre>
    source.isEmpty();
    </pre>
  */
  isEmpty<E>():Observable<boolean> {
    const isCurrentlyEmpty = values(this.entries).length == 0;
    return this.notifyOnEmpty.pipe(startWith(isCurrentlyEmpty), 
                                   switchMap((entries:E[])=>entries.length == 0));
  }

想法是商店可以打电话notifyOnEmpty.next(Object.values(this.entries))让订阅者知道商店是否是空的。

无论如何 switchMap 语句会导致错误:

[ts] '(entries: E[]) => boolean' 类型的参数不可分配给 '(value: E[], index: number) => ObservableInput' 类型的参数。类型 'boolean' 不可分配给类型 'ObservableInput'。(参数)条目:E[]

想法?

标签: javascriptangulartypescriptrxjsswitchmap

解决方案


switchMap运算符用于在每个值上选择一个新的 observable 。您只需要一个常规map,以便每个Array都映射到一个boolean

import { map, startWith } from 'rxjs/operators';

// ...

isEmpty<E>():Observable<boolean> {
  return this.notifyOnEmpty.pipe(
    startWith(values(this.entries)), 
    map((entries:E[]) => entries.length == 0)
  );
}

推荐阅读