2
votes

I can read in rxjs documentation (http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan) for the method scan there is a seed arguement.

In the below code, I would like to return a default value for _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;
   }
}

But the seed argument isn't return when I subscribe to the observable ex:

var channelsCatalog = new ChannelsCatolog();
channelsCatalog.getAllChannelsCatalog.subscribe((value) => console.log(value));
1
You might want to take a look at startWith() maybe that helps. - olsn

1 Answers

3
votes

The seed value of .scan is used for the first emission as accumulator. If no emissions have been done the scan operator does not execute.

You are looking for the .startWith operator which can be suffixed after your scan operator to let your stream upon subscription directly emit the value passed to startWith.

this._channels = this._updates
  .scan((channels: Channel[], operation: IChannelOperation) => operation(channels), initialChannel)
  .startWith(initialChannel)
  .publishReplay(1)
  .refCount();

You still need the seed of .scan otherwise after the initialChannel emission from .startWith it will take two emissions before the .scan will execute and return it's first value.