4

I have 2 observables, both http calls:

itemList$:Observable<any[]>;
newItem$:Observable<any[]>;

ngOnInit(){
  itemList$ = this.http.getList(...some url...) // returns array of many items
}

createNewItem(){
  newItem$ = this.http.createNewItem(...some url...) //returns array of one item
}

I would like to call the 'createNewItem()' function from elsewhere and I'd like the result to be merged with the current itemList$ observable results to form one array of items.

In the html I have an async pipe thats listening to itemList$:

<div *ngFor="let item of itemList$ | async">{{item.name}}</div>

How can I merge the newItem$ into itemList$ and have the async pipe display the merged results?

2 Answers 2

9

You can use Observable.merge (I have RxJS version 5.0.1)

Observable.merge(newItem$, itemList$)
          .subscribe(response => {
              // Perform your action
          });

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/merge.md

Sign up to request clarification or add additional context in comments.

2 Comments

if I use the .subscribe operator then I can't use the async pipe (which handles the unsubscribing automatically).
then don't use the async pipe but unsubscribe manually in OnDestroy or use the TakeUntilDestroy-plugin with the handy annotation to unsubscribe everything automatically.
1

You could use a Subject instead of Observables. As soon as you create a new item, hand it over to the Subject and emit it.

itemList$:AsyncSubjct<any>;

createNewItem(){
  this.http.createNewItem(...some url...).subscribe(data => {
    this.itemList$.next(data);
}

2 Comments

That seems to be the most common approach as I'm finding out. I thought there may be an operator that combines two Observables without the need for subjects.
Shouldn't muzurBurcu's suggestion work out for you as long as you don't subscribe? I personally like the Subjects since they inherit from Observables and can be used transparently without any overhead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.