使用 switchMap 发出一个热布尔值 observable?

Emitting a hot boolean observable using switchMap?

正在尝试创建一个使用 switchMap 发出热 Observable<boolean>isEmpty:Observable<boolean> 方法。这是我目前所拥有的:

  /**
   * 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] Argument of type '(entries: E[]) => boolean' is not assignable to parameter of type '(value: E[], index: number) => ObservableInput'. Type 'boolean' is not assignable to type 'ObservableInput'. (parameter) entries: E[]

想法?

switchMap 运算符用于 select 每个值的新观察值。您只需要一个常规 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)
  );
}