1

I'd like to know if this code has any sense or not:

let subs : Subscription;

// getObjectInfo retrieves object information from a MySQL DB
subs = this.ObjectService.getObjectInfo(item.id_obj)
        .subscribe(
          (retObject : any) => {
            // Process object here
          },
          (error) => {
            // Error in API call
          },
          () => {
            // IS THIS REDUNDANT OR UNNECESSARY?
            subs.unsubscribe();
          }); 

What I pretend is to make sure that the subscription is finished as soon as I get the info from the DB and I process it, but I don't know if this is a good way or if it's unnecessary...

The reason I'm asking this is because I see duplicate API calls sometimes and I wonder if they are because I didn't finish the subscriptions in a proper way or something like that.

Thanks!

Fel
  • 4,428
  • 9
  • 43
  • 94
  • 3
    You don't need to call `.unsubscribe()` when the Observable completes. Also see https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription – martin May 23 '18 at 14:43
  • Thanks for your comment, it's what I wanted to know. Regarding the linked article, I'm using the `takeWhile` operator in more complex components to unsubscribe from all subscriptions when the component is destroyed, but I've seen a more interesting method in the article (the `takeUntil` operator), so I'll do some tests. Cheers! – Fel May 23 '18 at 15:28
  • @martin you often need a crystal ball to know if an observable will complete on it's own. I'm just saying that when they designed observable they made this simple fact hard to be sure of. – Reactgular May 23 '18 at 15:29

1 Answers1

1

You can use take or first:

this.ObjectService.getObjectInfo(item.id_obj)
    .take(1) // or first()
    .subscribe(...)

So it will automatically unsubscribe after the first emission

Fabricio
  • 7,705
  • 9
  • 52
  • 87
  • Hi, I'll give a try to the `first` operator, thanks for the suggestion. – Fel May 23 '18 at 15:25
  • I think `take` throws an error if the count isn't emitted. While `first` will not throw an error if none are emitted. I once spent 2 days tracking down a bug because I used the wrong one. – Reactgular May 23 '18 at 15:31
  • I'll keep it in mind, thanks for the annotation, @cgTag. – Fel May 23 '18 at 15:40
  • @cgTag @Fel `take` doesn't throw, unless you use a negative parameter – Fabricio May 23 '18 at 15:49