我可以在rxjs文档(http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan)中阅读方法扫描,但是有一个种子争论。
在下面的代码中,我想为_channels Observables返回一个默认值。
export interface IChannelOperation extends Function {
(channels: Channel[]): Channel[];
}
let initialChannel: Channel[] = [];
@Injectable()
export class ChannelsCatalog{
defaultChannel: Subject<Channel> = new BehaviorSubject<Channel>(null);
private _currentChannel: Subject<Channel> = new BehaviorSubject<Channel>(null);
private _channels: Observable<Channel[]>;
private _updates: Subject<any> = new Subject<any>();
constructor(){
this._channels = this._updates
.scan((channels: Channel[], operation: IChannelOperation) => operation(channels), initialChannel)
.publishReplay(1)
.refCount();
}
getAllChannelsCatalog(): Observable<Channel[]>{
return this._channels;
}
}
但是当我订阅可观察的ex:
时,种子参数不会返回var channelsCatalog = new ChannelsCatolog();
channelsCatalog.getAllChannelsCatalog.subscribe((value) => console.log(value));
答案 0 :(得分:3)
.scan
的种子值用作第一次发射作为累加器。如果没有完成发射,则扫描操作员不会执行。
您正在寻找.startWith
运算符,该运算符可以在您的扫描运算符后加上后缀,让订阅后的流直接发出传递给startWith的值。
this._channels = this._updates
.scan((channels: Channel[], operation: IChannelOperation) => operation(channels), initialChannel)
.startWith(initialChannel)
.publishReplay(1)
.refCount();
你仍然需要.scan
的种子,否则在.startWith
的initialChannel发射之后,.scan
执行前将需要两次排放,并返回它的第一个值。