Home > Blockchain >  Should I use "$" sign suffix for Subjects in the RxJs and Angular?
Should I use "$" sign suffix for Subjects in the RxJs and Angular?

Time:11-22

So I have this question about $ sign suffix naming convention in the RxJs code and Angular specifically. In angular best practices documentation and in the overall I have found that we should use it when declaring the Observable, but haven't seen using it with Subjects. Why ? I thought it should mean "asynchronous". Moreover Subjects are Observables. So they are async and you have to subscribe to them. For now I started using $ with Subjects too. Is any real con of this practice ?

CodePudding user response:

$ suffix is used to indicate a certain variable is an observable. it helps to distinguish between normal variables and observables. its just a practice,

refer this to see the official doc explaining $ suffix. here

CodePudding user response:

On top of what Stoobish and Nipuna have said, I'd add that I like to have a $ as suffix as well to avoid ending up with a same variable name when working with an extracted value from a stream.

For example:

const currentTimeSeconds = currentTimeMs.pipe(
  map(currentTimeMs => currentTimeMs * 1000)
)

In the example above you'd end up with 2 variables named currentTimeMs. Sure that'd still work, but it's more confusing than helping. Sure you can rename the inner variable to something different as well. But overall I find it much clearer to have the following instead

const currentTimeSeconds$ = currentTimeMs$.pipe(
  map(currentTimeMs => currentTimeMs * 1000)
)

CodePudding user response:

Every subject is an observable.

If you look at Angular docs:

This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to use the same name with or without the “$”.

The $ sign suffix doesn't mean asynchronous, its used as a soft convention to indicate that the variable is a stream. It is more like a naming helper to indicate types.

  • Related