0

Hi I am new to angular and was learning the concepts of observable and Subject. What I understood was that observable are event emitters to which other code can subscribe to, and Subject can both both subscribe and emit data. I tried the below code where I check if time in milliseconds is even or not and based on that I am emitting success and failure. Basically I have created a random method for success and failure. The problem is whenever there is an error the control moves to error block but it never prints success or goes to success block. I am not sure what am I doing wrong. Please let me know also if you can point me to any blog or documentation which help in removing the gaps in my knowledge. Thanks in advance.

test() {
   const test_subject = new Subject<any>();
   var x = new Date();
   console.log(x.getMilliseconds());
   if (x.getMilliseconds() % 2) {
     //debugger;
     test_subject.next(true)
   } else {
     //debugger;
     test_subject.error(false);
   }
   return test_subject.asObservable();
 }


   callSubscription() {
       this.appService.test().
           subscribe(data => {
               console.log("success");
           }, error => {
               console.log("fail");
           });
   }
Amit Saha
  • 61
  • 3
  • 8

1 Answers1

1

From the RxJS documentation:

In an Observable Execution, zero to infinite Next notifications may be delivered. If either an Error or Complete notification is delivered, then nothing else can be delivered afterwards.

https://rxjs-dev.firebaseapp.com/guide/observable

This means that if you ever call error() or complete() you cannot call next() anymore unless you implement error handling or recreate your observable.

Damian C
  • 2,111
  • 2
  • 15
  • 17