简体   繁体   中英

How to get last emitted value of on Observable in the subscription when next is called after the subscription?

How can I subscribe and log the last value when next is called after subscription?

Here is the working demo stackblitz , how or is it possible to get value only the last value ie 123 that is emitted after the subscription inside the subscribe method or any other alternative? I used last() but it doesn't logs any value at all. I want the subscription to run only once and use the last value

    import { Component, Input, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { last } from 'rxjs/operators';

@Component({
  selector: 'hello',
  template: `
    <h1>Hello {{ name }}!</h1>
  `
})
export class HelloComponent implements OnInit {
  @Input() name: string;
  subject = new BehaviorSubject<any>({});

  ngOnInit() {
    this.subject.next(456);

    this.getData()
      // .pipe(last())
      .subscribe(console.log);

      // this next is being done in another component after subscription so putting it here to mimic the behavior
     this.subject.next(123);

  }

  getData(): Observable<any> {
    return this.subject.asObservable();
  }
}

You cannot use last() as the subject does not currently complete. You need to call complete() on the subject to be able to use it:

ngOnInit() {
  this.subject.next(456);

  this.getData()
    .pipe(last())
    .subscribe(console.log);

  this.subject.next(123);
  this.subject.complete();
}

Your StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM