Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an observable that produces a single value and never completes

I am aware of Observable.Never() as a way to create a sequence that never completes, but is there an extension/clean process for creating an observable that produces a single value and then never completes? Do i go with Observable.Create(...)? Observable.Concat(Observable.Return(onlyValue), Observable.Never<T>())? Or is there something built in or more "RXy" than this?

like image 432
el2iot2 Avatar asked Jan 29 '14 21:01

el2iot2


People also ask

How do you make a function Observable?

You can use Observable. defer instead. It accepts a function that returns an Observable or an Observable-like thing (read: Promise, Array, Iterators).

How do I create an Observable in RXJS?

Creating Observableslinkimport { Observable } from 'rxjs'; const observable = new Observable(function subscribe(subscriber) { const id = setInterval(() => { subscriber. next('hi'); }, 1000); });

How do you make an Observable subject?

We start by creating the subject, then create two Observers that will log each value they receive from the Subject (Observable). We tell the Subject to push the value 1 . We then create ObserverC which also logs each value it receives from the Subject. Finally, we tell the Subject to push the value 2 .

What does an Observable return?

An Observable is basically a function that can return a stream of values to an observer over time, this can either be synchronously or asynchronously. The data values returned can go from zero to an infinite range of values.


1 Answers

For your specific question, a simple choice is to use ‛Never‛ and ‛StartWith‛:

Observable.Never<int>().StartWith(5)

But for the more general case of "I have an observable sequence that will produce some results and eventually complete and I want to change it so it does not complete" (of which your question is a special case), your Concat idea is the way to do it

source.Concat(Observable.Never<int>());

or

Observable.Concat(source, Observable.Never<int>());
like image 193
Brandon Avatar answered Sep 19 '22 20:09

Brandon