tc39 / proposal-observable

Observables for ECMAScript
https://tc39.github.io/proposal-observable/
3.06k stars 90 forks source link

End a subscription if a completion token is returned #203

Closed alshdavid closed 1 year ago

alshdavid commented 4 years ago

I think an elegant way to manage self un-subscriptions is by seeing if a subscriber returns a cancelation token.

The token can be a static property on the Subscription class.

const source$ = new Observable(o => setInterval(o.next, 1000))

// Will unsubscribe after first event has been emitted
source$.subscribe(i => {
    console.log(i * 2)
    return Subscription.CompleteToken
})

This will allow for simple community driven "operator" functionality

source$.subscribe(rxpipe(
   first(),
   map(value => value * 2),
   console.log
))

// such as waiting for the first event and resolving the value via a promise
await source$.subscribe(first()).toPromise()
grimly commented 4 years ago

If you use the start event, you can do that :

const source$ = new Observable(o => setInterval(o.next, 1000))

// Will unsubscribe after first event has been emitted
source$.subscribe({
  start(sub) {this.sub = sub},
  next(i) => {
    console.log(i * 2);
    this.sub.unsubscribe();
  }
})