Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I complete Observable in RxJS

Tags:

Let's say we have an Observable:

var observable = Rx.Observable     .fromEvent(document.getElementById('emitter'), 'click'); 

How can I make it Complete (what will trigger onComplete event for all subscribed Observers) ?

like image 962
ulfryk Avatar asked Dec 04 '15 20:12

ulfryk


People also ask

How do you make an Observable complete?

I found an easier way to do this for my use case, If you want to do something when the observable is complete then you can use this: const subscription$ = interval(1000). pipe( finalize(() => console. log("Do Something")), ).

How do you know if Observable is complete?

The solution I came up with is to use a shared observable, save the request as a hot observable that way when the report button is clicked it will wait for the request or immediately generate if the request is complete.

How do I run Observable?

To execute the observable you have created and begin receiving notifications, you call its subscribe() method, passing an observer. This is a JavaScript object that defines the handlers for the notifications you receive.


2 Answers

In this present form, you cannot. Your observable is derived from a source which does not complete so it cannot itself complete. What you can do is extend this source with a completing condition. This would work like :

var end$ = new Rx.Subject(); var observable = Rx.Observable     .fromEvent(document.getElementById('emitter'), 'click')     .takeUntil(end$); 

When you want to end observable, you do end$.onNext("anything you want here");. That is in the case the ending event is generated by you. If this is another source generating that event (keypress, etc.) then you can directly put an observable derived from that source as an argument of takeUntil.

Documentation:

  • http://reactivex.io/documentation/operators/takeuntil.html
  • https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/takeuntil.md
like image 118
user3743222 Avatar answered Oct 04 '22 10:10

user3743222


What worked for me is using the take() operator. It will fire the complete callback after x number of events. So by passing 1, it will complete after the first event.

Typescript:

private preloadImage(url: string): Observable<Event> {     let img = new Image();     let imageSource = Observable.fromEvent(img, "load");      img.src = url;      return imageSource.take(1); } 
like image 25
Tomas Klingen Avatar answered Oct 04 '22 08:10

Tomas Klingen