Reputation: 11202
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:
save(title: string): Observable<never>
returns EMPTY
. This means subscriber's next()
will never be called. To let the observable chain continue with a single value, I pipe(defaultIfEmpty(true))
after calling save()
.
Pro: Function works and just call complete()
. save()
does not need to return a value with no meaning.
Con: Calling defaultIfEmpty(true)
to chain observable does not look intuitive.
Option 2:
save(title: string): Observable<boolean>
returns a value of(true)
. Function works, where both next()
and complete()
will be called once.
Pro: No need defaultIfEmpty(true)
to chain observable.
Con: next()
is always called. Is this considered a con?
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
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