Currently, I am in the process of creating a schedule for a community radio station and I need help updating the current show that is airing. I have considered polling the server once a minute as a temporary solution, but I am unsure if this is the most efficient approach.
I have been thinking about using the end time from the API to automatically update the show once it has ended, and then set up a new Observer with the next end time. Does anyone have any suggestions on how I can achieve this or perhaps a better method for updating the current show?
My main struggle at the moment lies in understanding Observables and Subscribers. How can I access the current end_time from radioShow$
to check if it has passed within an Observable.interval
, for example?
Your assistance with this matter would be greatly appreciated.
export class PlayerComponent {
radioShow$ = new BehaviorSubject({
start_time: new Date(),
end_time: new Date(),
radio_show: {
id: 0,
name: "Loading...",
});
constructor(
@Inject('api') private api,
private http: Http) {
Observable.interval(1000*60)
.switchMap(() => http.get(api + '/schedule/current/show')
.map(res => res.json()))
.subscribe(this.radioShow$);
}
}
View player.component.html:
<div class="io-radio-player">
<p class="schedule-times">{{(radioShow$ | async).start_time | date:"HH:mm"}}–{{(radioShow$ | async).end_time | date:"HH:mm"}}</p>
<h3 class="margin-none">
<a [routerLink]="['/radio-shows', (radioShow$ | async).radio_show.id]">{{(radioShow$ | async).radio_show.name | uppercase}}</a>
</h3>
</div>
@martins code works, but this is what I used in the end:
radioShow$ = new BehaviorSubject({
start_time: new Date(),
end_time: new Date(),
radio_show: {
id: 0,
name: "Loading..."
}
});
timer = new Subject();
@Component({
selector: 'app-player',
templateUrl: './player.component.html'
})
subject = new Subject();
let request = http.get(api + '/schedule/current/show')
.switchMap(() => http.get(api + '/schedule/current/show')
.map(res => res.json()))
.repeatWhen(() => this.subject)
.publishReplay()
.refCount();
request
.subscribe(this.radioShow$);
request
.map(response => {
// calculate the delay
return Math.abs(new Date(response.end_time).getTime() - (new Date()).getTime());
})
.concatMap(delay => Observable.of(null).delay(delay))
.subscribe(this.subject);