使用scan Observable

时间:2017-01-12 16:16:58

标签: rxjs observable

我可以在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));

1 个答案:

答案 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执行前将需要两次排放,并返回它的第一个值。