Issue an API request at a specific time in order to refresh the latest radio show in Angular2 utilizing RxJS

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

Answer №1

If you're looking to implement this functionality, one solution is to utilize the repeatWhen() operator along with an additional Subject to trigger the repetition:

let subject = new Subject();

const response = {
  start_time: new Date(),
  end_time: new Date(),
  radio_show: {
    id: 0,
    name: "Loading..."
  }
};

let radioShow$ = Observable.defer(() => {
    // return http.get(...);
    return Observable.of(response);
  })
  .do(() => console.log('create new HTTP request'))
  .repeatWhen(() => subject)
  .publishReplay()
  .refCount();

// responses
radioShow$
  .startWith(response)
  .subscribe(val => console.log('Response:', val));

// pooling delay
radioShow$
  .map(response => { // calculate the delay
    // return response.end_time - (new Date()).getTime();
    return Math.random() * 1000;
  })
  .concatMap(delay => Observable.of(null).delay(delay))
  .subscribe(subject);

Check out the live demo for a visual representation: https://jsbin.com/kutabiw/6/edit?js,console

This approach introduces random 0-3s delays between each call, mimicking real-world scenarios where such calculations are necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Separate string by using a regular expression pattern

Looking to parse a dynamic string with varying combinations of Code, Name, and EffectDate. It could be in the format below with all three properties or just pairs like Code-Name, Code-EffectDate, or Name-EffectDate. {"Code":{"value":"1"},"Name":{"value": ...

Guide on how to prevent click events when a checkbox is not selected in Angular 2

A click event is being used on a ul element with a checkbox below it. When the checkbox is checked, the list should be enabled and the click event should work. If the checkbox is unchecked, the list should be disabled and the click event should not work. ...

Unknown Element Error in Angular

Currently, I am working with Angular and Electron. I have successfully included ngx-quill in my module file. @NgModule({ imports: [ ~~~, QuillModule ], exports: [RouterModule] }) In addition, I have imported Quill into my main component file im ...

Issues with unit tests arising from property bindings in a reusable Angular modal component are causing failures

I have successfully developed a reusable Modal component that works perfectly fine when running ng serve without any errors in the console. However, I encountered an issue when running ng test where I received the error message "Template parse errors: Can& ...

Passing data from the front-end of an Angular component (app.component.html) to the back-end of another component (other.component.ts)

Imagine a scenario involving basic crud operations. Within the app.component.html file, there are multiple input fields and buttons. Upon clicking a button in app.component.html, the value of an HTML field is sent to the 'other.component.ts' comp ...

Angular 8 allows for dynamic updates as users provide input and make selections with check marks

When using Angular 8, if a user inputs "$10" and then clicks on it (using the OnClick event), the box below should be updated with the user input and the entire box should be selected like the example shown in the picture. I would greatly appreciate any t ...

Styling the checked state of a switch in NativeScript/Angular with ngModel/FormBuilder

Let's explore the styling of a switch element within Angular: <Switch class="switch" formControlName="answer"></Switch> One approach involves targeting the switch with checked attribute, setting its background-color and text color accord ...

Angular Universal does not fully render on the server side

Currently, my project involves integrating Angular 4 with Angular Universal and Knockout. The main objective is to have the Angular application generate HTML on the server side for SEO purposes. As part of this process, I need to utilize KnockoutJs to bin ...

Attempting to leverage the combination of mocha, ES6 modules, and ts-node while utilizing the --experimental-loader option

I've been attempting to make the ts-node option --experimental-loader function alongside mocha, but so far I haven't had any success. Before I started compiling ES6 modules, running mocha tests was as simple as: "test": "nyc --reporter=html mocha ...

Encountering an Angular 2 npm installation issue: (node:3240)

Seeking assistance with setting up a MEAN 2.0 example from this GitHub repository. After successfully running npm install on the server folder, encountering issues when executing npm install on the client folder (Angular 2), resulting in the following err ...

Error occurs when a value is passed to a component after it has already been checked for changes

Whenever I try to pass a value as input to a custom child component, I keep encountering the error message indicating that the expression has changed after being checked. The structure of the child component is as follows: <mat-card *ngIf="user$ | asyn ...

The parameters dictionary includes a null value, which is a parameter specified in the request body

I'm attempting to send an enum via a POST request to my WebAPI. The parameter is included in the request body and the controller is tagged with [FromBody]. Despite this, I am encountering a null entry error even though the parameter exists in the body ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Generating a font file using webpack in the monaco-editor package

We are currently in the process of integrating a new package into our project that has a dependency on the monaco-editor module. Let me provide you with some details about our project: We have ejected from the create-react-app project Our project is writ ...

Angular 4 Form remains valid even when an incorrect value is entered

Within my Angular 4 project, I encounter the issue of controlling input fields in multiple forms. Specifically, I need a mechanism to disable the save button if the input value is incorrect. For example, when I require an input field to only accept positi ...

invoking a function within an object in Typescript

export class MockedDataService { constructor(private Session: SessionService) {} private getMockedResponse(name:string){ return ""; // placeholder for the response data, will be a promise } public mocked:{ products:{ ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

Customizing font color upon hover in Next.js and Tailwind.css

Recently, I developed a Navbar component that displays a purple link when navigating to pages like Home or Projects. The issue arises when the background color is light; in this case, the link turns green on hover instead of staying purple. How would I adj ...

Converting information from a model into individual variables

I'm a newcomer to typescript and angular, and I've been attempting to retrieve data from firebase using angularfire2. I want to assign this data to variables for use in other functions later on. I am accustomed to accessing object members using d ...

How can you enhance a component by including additional props alongside an existing onClick function?

As a newcomer to React and TypeScript, I've created a simple component that looks like this: const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => { const classes = useStyles(); return <CloseIcon className={classes.closeButto ...