如何根据用户选择有条件地 return 使可观察对象成为流?

How do I make an observable conditionally return a stream based on user selection?

正在尝试构建一个有条件地从两个来源读取的可观察流。基于用户 selection 的文件流,或当前会话的内存中流。

我有一个下拉菜单,用户可以在其中 select 以下其中一项:

Current  //in-memory stream contains entries (error, warning, trace, debug) as they happen for the current session
Error    //error.log file entries
Warning  //warning.log
Trace    //trace.log
Debug    //debug.log

这是我的 observable

的设置代码
    //save the in-memory stream as a local variable so it returns the same instance
    let current$ = this.$loggerService.applicationLog$

    this.logs$ = this.logSeveritySubject
        .asObservable()
        .startWith(this.applicationLogName) //the currently selected value
        .flatMap((fileName: string) => {
            if (fileName === "current") {
                return current$;
            }

            return this.$localStorageService.readAsStringAsync(filename).map((s) => {
                let a: any[] = s.split(/\r\n|\r|\n/).filter(n => n.length > 0);
                return a.reverse();
            });
        })
        .merge(this.clearLogSubject.asObservable()) //used to reset the scan back to an empty array
        .scan((x, y) => {
            if (y === null) return [];
            return y.concat(x);
        }, []);

现在,当用户 select 有一个新值时,我会通过主题推送一个新的日志文件名

this.clearLogSubject.next(null); //reset the scan back to an empty array
this.logSeveritySubject.next(this.applicationLogName); //read from the user selected option

我遇到的问题是,在两个流之间切换开始 return 重复条目(因为内存中的流可能永远不会完成?)。这让我想到,当return current$;运行多次时,它实际上多次将同一个实例放入最终的可观察流中。

也许有更好的编码方式。我基本上希望用户 select 从哪个日志源查看。唯一需要注意的是,内存中的可观察对象永远不会关闭,因为它可以随时写入。

您正在使用 flatMapmergeMap) that merges events from all observables that come to it hence the duplicate entries. Use switchMap 的别名,因为它仅使用最后一个可观察到的事件。