2017-11-10 53 views
0

我是RxJS的新手。我正在使用RxJs 5.5.2使用reduce主题没有完成调用

为了保持简单,我希望每次在主题上调用next时都返回缩小的值。下面是一个示例代码:

const sub = new Subject<number>(); 
const obsesvable = sub.pipe(
    reduce((a, b) => { 
    return a + b; 
    }, 0) 
); 

obsesvable.subscribe(x => console.log(x)); 

sub.next(2); 
sub.next(3); 
// if I don't call this nothing happens 
sub.complete(); 

现在,如果我不叫sub.complete()什么也没有发生。

如果我拨打sub.complete()我不能再使用sub.next()发送值;

回答

1

看看reduce方法的marble diagram

enter image description here

当流结束这将只能发出,这就是为什么你没有什么,直到你打电话complete

如果要“减少”,并随着时间的推移,你应该相当使用的值scanenter image description here

所以,你的代码应该宁可:

const sub = new Subject<number>(); 
const obsesvable = sub.pipe(
    scan((a, b) => { 
    return a + b; 
    }, 0) 
); 

obsesvable.subscribe(x => console.log(x)); 

sub.next(2); 
// output: 2 
sub.next(3); 
// output: 5