【问题标题】:How do I make an observable conditionally return a stream based on user selection?如何根据用户选择使 observable 有条件地返回流?
【发布时间】:2017-01-10 06:21:35
【问题描述】:

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

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

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);
        }, []);

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

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

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

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

【问题讨论】:

    标签: angular typescript ionic2 rxjs5


    【解决方案1】:

    您正在使用flatMapmergeMap 的别名)合并来自所有可观察到的事件,因此出现重复条目​​。请改用switchMap,因为它仅使用上次可观察到的事件。

    【讨论】:

    • 也许只有我一个人,但 RxJs 库的好例子严重缺乏。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2014-04-16
    • 2022-01-10
    相关资源
    最近更新 更多