Home > other >  when i subscribe my Observable, my next is not working
when i subscribe my Observable, my next is not working

Time:04-09

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

CodePudding user response:

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));
  • Related