简体   繁体   English

如何在 rxjs 中创建可观察的瀑布?

[英]How to create a waterfall observable in rxjs?

I am sure a waterfall observable isn't a thing, but it best describes what I want to do.我确信可观察到的瀑布不是一件事,但它最好地描述了我想要做的事情。

Code代码

Given is a map of paths and behavior objects that represent their content.给定的是代表其内容的路径和行为对象的映射。

const pathmap = new Map<string, BehaviorSubject<string>>();
pathmap.set("foo.txt", new BehaviorSubject<string>("file is empty"));
pathmap.set("bar.txt", new BehaviorSubject<string>("file is empty"));

Also given is a BehaviourSubject that contains the active path.还给出了一个包含活动路径的 BehaviourSubject。

const activePath = new BehaviorSubject<string | null>(null);
...
activePath.next('bar.txt');

What I need:我需要的:

I want to create a single chained Observable that triggers an event when:我想创建一个在以下情况下触发事件的单链 Observable:

A) The active file path got changed. A) 活动文件路径已更改。

B) The content of a file got changed. B)文件的内容发生了变化。

What I have so far:到目前为止我所拥有的:

https://codesandbox.io/s/bold-dream-3hfjdy?file=/src/index.ts https://codesandbox.io/s/bold-dream-3hfjdy?file=/src/index.ts

function getFileContentObservable(): Observable<string> {
  return currentFile.asObservable()
    .pipe(map((path: string) => pathmap.get(path).asObservable()))
    .pipe(map((content: string) => `<h1>${content}</h1>`));
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          Type 'string' is not assignable to type 'Observable<string>'
}

How would I chain this?我将如何链接这个?

Try switchMap Operator.尝试switchMap运算符。

function getFileContentObservable(): Observable<string> {
  return currentFile.asObservable().pipe(
    filter(Boolean),
    switchMap((path: string) => pathmap.get(path).asObservable()),
    map((content: string) => `<h1>${content}</h1>`)
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM