gpt4 book ai didi

javascript - 使用 switchMap 发出一个热 bool 值 observable?

转载 作者:行者123 更新时间:2023-11-30 20:11:04 25 4
gpt4 key购买 nike

尝试创建 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] 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 运算符用于在每个值上选择一个新的可观察对象。您只需要一个常规的 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)
);
}

关于javascript - 使用 switchMap 发出一个热 bool 值 observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52414920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com