kctang
kctang

Reputation: 11202

Observable 'save' should return EMPTY or a dummy value

I see a common pattern in my application where functions return Observables that do not need to provide a next() value (i.e. save()) but may be part of an Observable chain.

In this working example (link below), I have a demo BookService with save() and getBooks(). The code example save 2 books, get books from service and console.log the books via a single observable chain.

I have tried these two options:

Option 1:

Option 2:

Option 3:

The code example provides both option 1 and option 2 (commented).

Question: What should functions like save() return? Are there written documentation/article on observables design for such scenario?

Appreciate your thoughts on this.

Upvotes: 0

Views: 178

Answers (1)

Mark van Straten
Mark van Straten

Reputation: 9425

My understanding is that it depends on your usecase. Using Observables allows you to implement cancellation behaviour for your .Save() function. If it returns a value or just completes is up to you. Depending on your usage (are you always piping defaultIfEmpty onto it?) you can either go for the pure version (no value, just complete) or let it default to a value to make it easier on yourself.

What is important is that you document the behaviour the consumers of your .Save() function can expect of your observable. Will it indeed emit only a true value and complete? Or never emit a value?

Upvotes: 1

Related Questions