DEV Community

Discussion on: Observables are promises on steroids

Collapse
 
andywer profile image
Andy Wermke • Edited

How do I listen to .once('all-unsubscribed') event?

function subscribeToThings() {
  return multicast(new Observable(observer => {
    // <Subscribe to things>

    const terminateSubscription = () => {
      // <-- THIS IS THE "all-unsubscribed" CODE
      // Remember? multicast() makes that all downstream subscriptions are bundled into one,
      // so this is the callback function that will be run when this bundled subscription is terminated
    }

    return terminateSubscription
  }))
}

subscribeToThings().subscribe(/* ... */)

Otherwise, it is possible to use Subject, as in thread.js?

Sure, who would stop you? ;)

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt

Currently, I use the signature,

Observable<{
      value?: QueryItemPartial
      i: number
      cancelFunction: CallbackType
    }>

Will it work?

Thread Thread
 
andywer profile image
Andy Wermke

That doesn't make much sense. Why would you want to emit a new cancellation function for every new value?

You shouldn't have this non-standard custom cancellation approach when there is already a standardized one (observable.subscribe(), subscription.unsubscribe()). Keep in mind that emitting functions is generally considered to be an anti-pattern.

Maybe the observable-fns readme lacks a link to some documentation about observables in general… I guess this is one of your first times using observables? (No offense – I'm seriously interested :) )

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt

Yes. Only promises and eventemitters.

Should I start with RxJS?

Thread Thread
 
andywer profile image
Andy Wermke

Yeah, maybe that's the best to get started. You should definitely start with RxJS's documentation – it's pretty good!

Which library you then use doesn't really matter too much as their APIs are very similar to almost identical.

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt

const terminateSubscription = () =>

Do you actually mean

new Observable((obs) => {
  return terminateSubscription
  // I actually use
  // return () => { isUnsubscribed = true }
})
Thread Thread
 
andywer profile image
Andy Wermke

Yes, my bad! I updated my code sample accordingly.