Benjamin M
Benjamin M

Reputation: 24527

Angular2 + async pipe: Get multiple values from a single Observale

I have a single Service, which returns a single Observable. Now I'm looking for the correct / most efficient way to get multiple results from this Observable without writing too much code.

Here's my current code:

@Injectable()
export class MyService {
  foos = new BehaviorSubject<Array<Foo>>([]);

  getFoos() {
    return this.foos.asObservable();
  }
}



@Component({
  template: `
    Total: {{ totalCount | async }}
    Omitted: {{ (totalCount | async) - (maxFiveItems | async).length }}
    <div *ngFor="let item of maxFiveItems | async">
      {{item.bar}}
    </div>
  `
})
export class MyComponent {
  totalCount: Observable<number>;
  maxFiveItems: Observable<Array<Foo>>;

  constructor(myService:MyService) {
    this.totalCount = myService.getFoos()
        .map(arr => arr.length);

    this.maxFiveItems = myService.getFoos()
        .map(arr => arr.slice(0, 5));
  }
}

The result looks fine, but I'm using the async pipe 4 times. Which (as far as I know) will result in 4 Subscriptions. This shouldn't be necessary at all I guess (?)


Of course I could manually subscribe within the constructor of MyComponent and then live without async pipes. But then I have to take care of unsubscribing myself.

Is there any other way to handle this?

Upvotes: 4

Views: 1853

Answers (1)

martin
martin

Reputation: 96899

There's nothing wrong with what you're doing assuming that myService.getFoos() somewhere inside uses share() operator so all your async pipes share the same subscription to the source. If you're using BehaviorSubject as in this example then you're fine.

What you mentioned about subscribing yourself in the constructor is what came to my mind immediately. I don't see manual unsubscription as a problem though.

Upvotes: 4

Related Questions