Ahamed Ishak
Ahamed Ishak

Reputation: 1062

Angular Rxjs Observable items count doubles on subscribe

I'm creating an observable using an array. When I call subscribe method its length becomes doubles.

ie. if array has 3 items after subscribe it becomes 6 by duplicating same items.

I'm also using async pipe to list down items in html.

Please check the plunker example

@Component({
selector: 'my-app',
template: `
 <div>
   <ul>
      <li *ngFor="let data of obs|async">
      {{data.name}}
      </li>
   </ul>
 </div>
 `
 })

export class App  implements OnInit{

obs: Observable<any>;

arr = [{
   name: 'name1',
   age: 26
  }, {
   name: 'name2',
   age: 27
  }, {
   name: 'name3',
  age: 28
  }];

  constructor() {

  }
  ngOnInit() {

   this.obs = Observable.from(this.arr).toArray()


   this.obs.subscribe(res => {

    console.log(res)
   })
  }
}

Output :

Upvotes: 0

Views: 92

Answers (1)

Frederik Prijck
Frederik Prijck

Reputation: 1509

In a JSFiddle, this is working fine for me: https://jsfiddle.net/dcuLggwa/1/

I'm not sure why you are using: this.obs = Observable.from(this.arr).toArray() ? You can use : this.obs = Observable.of(this.arr), which results in the same behavior: https://jsfiddle.net/dcuLggwa/2/

I've updated the plunkr to use Observable.of instead of Observable.from(...).toArray() and it's working fine: https://plnkr.co/edit/vaMK6G5AxCSs2kCIJ2h8?p=preview

The difference between Observable.from(...).toArray() and Observable.of:

Observable.from emits every item from the array seperatly, toArray wait until the observable completes and then emits all the items (which are emitted seperatly) as an array. So basicly you start with an array, split it into seperate items and combine it again in an array.

Observable.of creates an Observable which emits the item being passed to the of() operator.

Upvotes: 1

Related Questions