How to create an observable from a function?

I want to call a function (synchronously) and then use its return value as the initial emission (subsequently linking some other operators to the resulting observable).

I want to call this function during subscription, so I can’t just use it Observable.of(() => getSomeValue()). I saw bindCallback(previously fromCallback), but I do not think that it can be used for this task (correct me if I am wrong). I saw the static operator startin the v4 docs, but apparently it is not implemented in version 5 (and no indication that it is on the way). RxJava also has a statement fromCallablethat does just that afaik.

The only way I could think:

Observable.create((observer: Observer<void>) => {
  let val = getSomeValue();
  observer.next(val);
  observer.complete();
})

which, I think, does just that. But it just seems so complicated for a simple thing that probably should have looked like Observable.fromFunction(() => getSomeValue())What if I want to run it asynchronously, like an operator start? How can I do this in the current RxJS rule?

+4
source share
3 answers

I try to avoid explicit use Observable.createwhere possible, because it is usually a source of errors that have to control not only your emission of events, but also your break logic.

Observable.defer. , Observable Observable-like (: Promise, Array, Iterators). , , , , :

Observable.defer(() => doSomethingAsync());

, , :

Observable.defer(() => Observable.of(doSomethingSync()));

. create, . , Observable.bindCallback, . , , multicasting.

+4

, - Observable.create, .

, , startWith() ( , getSomeValue() ).

Observable.bindCallback . , , , , , Observable.create.

+1

fromFunction$, :

function fromFunction$(factory: () => any) {
  return Rx.Observable.create((observer) => {
    try {
      observer.next(factory());
      observer.complete();
    } catch (error) {
      observer.error(error);
    }
  });
}

:

fromFunction$(() => 0).subscribe((value) => console.log(`Value is '${value}'`), null, () => console.log('Completed'));
fromFunction$(() => [1, 2, 3]).subscribe((value) => console.log(`Value is '${value}'`), null, () => console.log('Completed'));
fromFunction$(() => { throw 'Something' }).subscribe(null, (error) => console.error(`Error: ${error}`));

:

Value is '0'
Completed

Value is '1,2,3'
Completed

Error: Something

.

0

Source: https://habr.com/ru/post/1665541/


All Articles