简体   繁体   中英

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

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?

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.

$ 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

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)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM