Renaud
Renaud

Reputation: 4668

returning vs exposing observable in angular services

I've seen two ways of interfacing with observables in angular services:

public getSomeData(): Observable<FooData> { ... }
// or
public someData$: Observable<FooData>;

The obvious difference is that using a method creates a new Observable instance for every invocation, where the second choice shares the same Observable instance (usually created in the constructor).

What are the pros and cons to both approaches? What should I consider when choosing between the two?

Upvotes: 1

Views: 498

Answers (2)

kos
kos

Reputation: 5364

IMHO. In short:

  • method approach is a better fit for business logic layer and services requesting APIs

  • property approach is better for state-related services (like ngrx) and external event sources

Long answer:

With method you get direct interaction with the Observable, thus you can directly set request params, complete it prematurely, etc. Usually data params here differ from request to request (think categories or pages in an API request). Example:

Service that fetches products by category.

And two widgets on a page that display two different categories.

--

With property you can share data on Observable amongst many parts of your application, though interaction requesting data on it is more indirect (think ngrx, websocket, external event source like window scrolling). Benefit here is that its centralized and wont have duplicate requests. Example:

Service that fetches logged in user data, and that data will be used among whole application.

In the service you'll have methods to update and reset it + one Observable, that all related parties would subscribe to

--

Hope it helps

Upvotes: 1

user4676340
user4676340

Reputation:

What you said isn't true, and I can list more than that :

public SomeData$() { ... }
public someData$ = new XXX(...);
public get someData$() { ... }
public someData$ = () => { ... }

They all do the same thing, which is what you choose to do with them.

The implementation is the difference, but the syntax doesn't change anything.

To answer you it depends on the type of observable, and the type of use you do with it.

Observables can be hot, or cold.

Cold observables are observables that emit a single stream, then stop. HTTP calls are like that, or results of of() calls are too.

Hot observables are observables that keep listening. Subjects are like that.

You have to use them for what they're useful for, but you don't rely on the syntax to do that.

Choose the syntax you want, and enforce it in your team.

For instance, in mine, we tend to use hot observables as data sources, and we expose the observable with a variable referencing it.

Upvotes: -1

Related Questions