我可以在rxjs文档(http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan)中读到方法扫描有一个种子参数。
在下面的代码中,我想返回_channels可观察量的默认值。
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));
.scan
的种子值用于作为累加器的第一次发射。如果未进行排放,则不会执行扫描运算符。
您正在寻找可以在扫描运算符后加上后缀的.startWith
运算符,以使订阅后的流直接发出传递给 startWith 的值。
this._channels = this._updates
.scan((channels: Channel[], operation: IChannelOperation) => operation(channels), initialChannel)
.startWith(initialChannel)
.publishReplay(1)
.refCount();
您仍然需要.scan
种子,否则在初始 Channel 从 .startWith
发射之后,在.scan
执行并返回其第一个值之前,它将需要两次发射。