【发布时间】: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