Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

when i subscribe my Observable, my next is not working

myObservable():Observable<boolean>{
  const result = new Subject<boolean>();
  result.next(true);
  result.complete();
  return result.asObservable();
}

this.myObservable().subscribe(x=> console.log(x));

when i subscribe my Observable which function name is myObservable
but the console never working

this.myObservable().subscribe({
next: _response => {console.log('next');}
        error: error => {
            console.log('had an error');
       },
       complete: () => {
           console.log('complete');
           this.accountDataLoaded = true;
       }})

try the life cycle console
the complete was print but next is not

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code does :

  • Create an Observable
  • Emit a value : true
  • Complete the Observable
  • return the Observable
  • Subscribe to the next values from the Observable

Of course, no new values are emitted. That is why the callback will never be executed.

As an example, you can use a timeout if you want to emit the values after the subscription :

function myObservable():Observable<boolean>{
  const result = new Subject<boolean>();
  setTimeout(() => {
    result.next(true);
    result.complete();
  }, 1000)
  return result.asObservable();
}
this.myObservable().subscribe(x=> console.log(x));

But, as you created a Subject, you could also use a ReplaySubject which emits old values to new subscribers

function myObservable():Observable<boolean>{
  const result = new ReplaySubject<boolean>();
  result.next(true);
  result.complete();
  return result.asObservable();
}

this.myObservable().subscribe(x=> console.log(x));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading