javascript - 使用 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[]
想法?
解决方案
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)
);
}
推荐阅读
- c++ - 从文本文件中读取并保存到列表
- r - 将 API 保存为环境变量(用于在 R 中设置 monkeylearn)
- node.js - 无法在 Lambda 函数中的模块外部使用导入语句
- java - 在 MacOS 10.15.1 (Catalina) 上安装 SOAPUI 5.5.0 的问题
- java - 无法通过 RMI 在 JackRabbit 中加载节点类型
- powershell - 当行为空/空白时,如何有效地删除多行字符串的最后一行?
- python - 在启动 docker 服务时运行多个命令
- elasticsearch - GET 列出 ElasticSearch5 上的所有索引
- javascript - 是否有通过拖放重新排序firebase中的数据并保存的功能?
- html - eBay 皮肤无法在 HTML 网页上运行,但已成功安装