cdxf
cdxf

Reputation: 5648

How to merge the emitted value from a source with the previous value

Assume that I have these Observables:

let users: Observable<User[]> //all the users

let receivedUsers: Observable<User[]> //only a subset of users get from http

How to make the users emit the merged array when the receivedUsers emits:

receivedUsers: [1]  .... [2]    ..... [3,4]       ..... [5,6]

users        : [1]  .... [1,2]  ..... [1,2,3,4]   ..... [1,2,3,4,5,6]

Upvotes: 0

Views: 294

Answers (1)

kauppfbi
kauppfbi

Reputation: 825

I am not quite sure about your requirement, but I think this is what you are looking for:

export class Service {
  private users: User[] = [];
  private usersSubject: BehaviourSubject<User[]> = new BehaviourSubject();

  constructor(){
    // whereever it comes from
    // also consider a Set<User> if you want to avoid duplicates
    usersReceived.subscribe(users => {
     this.users = [...this.users, users];
     // this.users = this.users.push(users);
     this.usersSubject.next(this.users);
    });
  }

  public getAllUsers: Observable<User[]> {
    return this.usersSubject.asObservable();
  }
}

If this doesn't meet your needs, then you should have a look on the rxjs operators in general, but especially to merge, mergeAll and mergeMap. See the official documentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html

Upvotes: 1

Related Questions