检查是否未完成 Observable 为空

vad*_*shb 5 javascript rxjs typescript rxjs5

有没有一种好方法可以检查未完成的 Observable 在那个确切时间是否为空?

let cache = new ReplaySubject<number>(1);
...
// Here I want to know if 'cache' still empty or not. And, for example, fill it with initial value.
cache.isEmpty().subscribe(isEmpty => {
    if (isEmpty) {
        console.log("I want to be here!!!");
        cache.next(0);
    }
});
// but that code does not work until cache.complete()
Run Code Online (Sandbox Code Playgroud)

ols*_*lsn 2

你可以使用takeUntil()

Observable.of(true)
    .takeUntil(cache)
    .do(isEmpty => {
        if (isEmpty) {
            console.log("I want to be here!!!");
            cache.next(0);
        }
    })
    .subscribe();
Run Code Online (Sandbox Code Playgroud)

然而这只会工作一次。


另一种方法是“清空”缓存并使用以下命令将其初始化为空BehaviorSubject

let cache = new BehaviorSubject<number>(null as any);
...
cache
   .do(content => {
       if (content == null) {
           console.log("I want to be here!!!");
           cache.next(0);
       }
    })
    .subscribe();
Run Code Online (Sandbox Code Playgroud)

当然,您可以立即使用一些默认值初始化缓存。

  • 此外,`BehaviorSubject` 有一个方法 [getValue](http://reactivex.io/rxjs/file/es6/BehaviorSubject.js.html#lineNumber21),它返回当前值(如果有)。 (2认同)