Currently learning RxJS. I have an integer selectedCourseIndex within a service that I\'d like a separate component to subscribe to.
courses-sec
Correct me if i am wrong,
Your problem: you want the current (or latest) value that an observable has irrespective of whether someone has emitted a value right now or not.
Answer: A Subject or Observable doesn’t have a current value. When a value is emitted, it is passed to subscribers and the observable is done with it. Observable will only come to action when another value is emitted to the subject stream.
If you want to have a current value, use BehaviorSubject which is designed for exactly the purpose you need, it keeps the last emitted value, irrespective of when it was emitted and immediately conveys that to new subscribers.
Note: It also has a method getValue() to get the current value.
another problem you are facing.
Problem: your current code doesn’t seems to work.
Answer: Let me give an example as how i work with Observable -
Courses-action.service.ts
import { Injectable } from ‘@angular/core’;
import { Subject } from ‘rxjs’;
@Injectable()
Export class CoursesActionService {
Public selectedCourseIndexUpdated = new Subject();
Public isCourseIndexUpdated$ = this.selectedCourseIndexUpdated.asObservable();
Public announceSelectedCourseIndex(response: any) {
this.selectedCourseIndexUpdated.next(response);
}
Some random file who emits a value to the subscriber -
this.coursesActionService.announceSelectedCourseIndex(453);
Some random file who listens to the emitted value -
this.coursesActionService.isCourseIndexUpdated$.pipe(takeUntil(this.destroyed$))
.subscribe(res => console.log(‘i have the response’, res));