Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling observer.complete() is required after observer.error()?

I am writing an observable in Angular 2. My code is something like:

Observable.create(observer => {
    // fetched something from web service
    if (some condition) {
        observer.next('something');
        observer.complete();
    }
    else { // error with no data
        observer.error('something else');
        observer.complete(); // Is this required here? Or can I skip this in case of error() ?
    }
});
like image 899
Akhilesh Shukla Avatar asked Nov 10 '17 10:11

Akhilesh Shukla


People also ask

What is Observer complete () in angular?

The observer's complete() callback specifies the action to take when the observable has completed producing and emitting data. const observer = { complete: () => console. log('You have used up all the vowels.') }; Js.

What is Observer complete?

1. Complete Observer. This is a detached observer where the researcher is neither seen nor noticed by participants. It's one way of minimizing the Hawthorne Effect as participants are more likely to act natural when they don't know they're being observed.

What is Observer in rxjs?

What is an Observer? An Observer is a consumer of values delivered by an Observable. Observers are simply a set of callbacks, one for each type of notification delivered by the Observable: next , error , and complete .

What is observable Observer and subscribe in angular?

Observable are just that — things you wish to observe and take action on. Angular uses the Observer pattern which simply means — Observable objects are registered, and other objects observe (in Angular using the subscribe method) them and take action when the observable object is acted on in some way.


1 Answers

You don't need to call complete, it won't do anything anyway because you called error already.

Doc says: http://reactivex.io/documentation/observable.html

By the terms of the Observable contract, it may call onNext zero or more times, and then may follow those calls with a call to either onCompleted or onError but not both, which will be its last call

You can have a look at the source code:

  • https://github.com/ReactiveX/rxjs/blob/master/src/Subscriber.ts#L120

  • https://github.com/ReactiveX/rxjs/blob/master/src/Subscriber.ts#L108

like image 85
martin Avatar answered Oct 23 '22 03:10

martin