gkucmierz
gkucmierz

Reputation: 1145

Immediate response after subscribtion

This is my theoretical service:

@Injectable({
  providedIn: 'root'
})
export class DataService {
  @Output() data: EventEmitter<number> = new EventEmitter();

  constructor() {
    setInterval(() => {
      this.data.emit(Math.random());
    }, 1e3);
  }
}

And my component:

  ngOnInit() {
    this.sub = this.dataService.data.subscribe(data => this.data = data);
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

Works good, I have new data when it comes. But how to change my DataService to provide data immediately after subscription. I mean, I want to store last data (in this theoretical case random number) and provide it right after subscription. Is this even possible using rxjs?

Upvotes: 1

Views: 202

Answers (1)

bryan60
bryan60

Reputation: 29335

  1. don't use event emitters in place of subjects, they are not guaranteed to always follow the observable contract

  2. don't use an output in a service, it applies to components and directives only

  3. use a behavior subject to have new subscribers immediately get the last emitted value upon subscription

  4. good practice to make subjects private and expose a public observable

Like so:

 @Injectable({
   providedIn: 'root'
 })
 export class DataService {
   private data: BehaviorSubject<number> = new BehaviorSubject(null); // initialize to whatever
   data$: Observable<number> = this.data.asObservable();

   constructor() {
     setInterval(() => {
       this.data.next(Math.random()); // use next for subjects
     }, 1e3);
   }
 }

Upvotes: 3

Related Questions