33

Is there any differences between

Observable.pipe(take(1)).subscribe(...)

vs

const subscription = Observable.subscribe(() => {
   // Do something, then
   subscription.unsubscribe()
})
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
Tuong Le
  • 18,533
  • 11
  • 50
  • 44
  • Possible duplicate of [Difference between .unsubscribe to .take(1)](https://stackoverflow.com/questions/40563065/difference-between-unsubscribe-to-take1) – quetzalcoatl Jan 09 '19 at 10:33

2 Answers2

27

The take(1) approach has a number of advantages over subscribe:

  1. Code readability (and elegance).
  2. The second approach requires that you hold and manage extra variables.
  3. The second approach will not invoke the complete handler. This is because .take(1) actually create a new observable which potentially yields a single item and completes.
  4. The second approach will work for the trivial case of taking a single element, but if you need to take more then 1, take(4) will stay simple while the second approach will become hard to code.

The 3rd item is the rxjs related one, the others relate to coding style.

Have a look at a sample here.

mik01aj
  • 11,928
  • 15
  • 76
  • 119
Meir
  • 14,081
  • 4
  • 39
  • 47
8

In Angular2, I find myself using both paradigms.

The first makes the most sense inside of a method, where as the second is better used in a constructor, with a cleanup in the deconstructor.

doThing(){
    this.store.select('thing').pipe(take(1))
        .subscribe(item => {
            otherMethod(item)
        });
}

vs

class SomeClass{
    public val;
    private sub;
    constructor(){
        this.sub = this.store.select('thing')
            .subscribe(item => {
                this.val = item
            });
    }
    ngDestroy() {
        this.sub.unsubscribe()
    }
}
joeydale
  • 81
  • 3