Home > Back-end >  How to create a waterfall observable in rxjs?
How to create a waterfall observable in rxjs?

Time:07-20

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.

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:

A) The active file path got changed.

B) The content of a file got changed.

What I have so far:

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?

CodePudding user response:

Try switchMap Operator.

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