Issues with setInterval function in RxJs 6+

I am currently diving into RxJs and have set up an Observable that emits various values. However, when trying to incorporate a SetInterval for one of the values, it seems like the emission is not happening during that interval. Are there any alternative functions I should be using or could I possibly be overlooking something else?

Check out the code snippet below:


import { Observable } from 'rxjs/Observable';
import { from, interval } from 'rxjs';

var observable = Observable.create(function subscribe(observer: any) {
    try {
        observer.next('Hey guys!');
        observer.next('How are you?');
        
        setInterval(() => {
            observer.next('I'm good');
        }, 3000);
        
        observer.complete();
        observer.next('After Complete');
    } catch (error) {
        observer.error(error);
    }
});

var timeObservable = interval(1000);
var timeSubscriber = timeObservable.subscribe((sec: any) => {
    console.log(sec);
});

var observer = observable.subscribe((x: any) => addItem(x),
                                    (error: any) => addItem(error));

function addItem(val: any) {
    var node = document.createElement("li");
    var textNode = document.createTextNode(val);
    node.appendChild(textNode);
    document.getElementById("output").appendChild(node);
}

Answer №1

Ah, I found the solution! Once the code reached the setInterval with a timeout interval of 3000, the Observable completed() and stopped emitting values. To keep the values emitting continuously, I removed the complete() method and added unsubscribe() to stop after 6001 milliseconds.

import { Observable } from 'rxjs/Observable';
import { from,interval } from 'rxjs'


var observable = Observable.create(function subscribe(observer : any){
try{
   observer.next('Hey guys!')
   observer.next('How are yu ??')

   setInterval(()=>{
    observer.next('I m good')
   },1000)
   }
    catch(error)
    {
        observer.error(error)
    }
});


// var timeObservable = interval(1000);
// var timeSubscriber = timeObservable.subscribe((sec: any)=> 
// {console.log(sec)});


var observer= observable.subscribe((x: any)=> addItem(x),
                    (error: any)=> addItem(error));

                    setTimeout(function(){
                        observer.unsubscribe()
                    },6001)

function addItem(val: any)
{
    var node = document.createElement("li");
    var textNode = document.createTextNode(val);
    node.appendChild(textNode);
    document.getElementById("output").appendChild(node);
}

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

The application's functionality is interrupted when router.navigate() is called within the .subscribe method

I am having an issue with user navigation on my application. After successfully signing in, users get redirected to the home page (/), but they are unable to navigate by clicking any links on that page. Upon further investigation, I discovered that moving ...

Prevent the function from affecting type deduction

I am working with a type similar to this: interface Test<R, T> { inputType: R; transformer: (input: R extends any ? R : never) => T; } // function for inferring type function inferTest<T extends Test<any, any>>(t: T): T { ...

The lack of change detection triggering in Angular 8's UI observables could be due to the default setting of ChangeDetection

I am facing a situation where I have a container component with a service injected into it. The service holds an observable, and I am binding this observable to a child component's input property in the container component's template using an asy ...

Is it possible to refresh the component view using the service?

I am interested in developing a NotificationService that will be utilized to showcase a notification from another section. My inquiry is, how can I refresh the view of a component using a service? My ultimate goal is to have the capability to embed a comp ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Enhance the API response for Angular service purposes

I am currently working on modifying the response returned by an API request. At the moment, I receive the response as: [ { name: "Afghanistan" }, { name: "Åland Islands" } ] My goal is to adjust it to: [ { name: "A ...

Mongoose fails to add an object to an array

I am facing an issue with my express application where comments are not being inserted into posts. Even though there are no errors displayed, the comments are not being added when posting via Postman. I have tried various solutions like this and this, but ...

Is it possible to use optional destructured arguments in a Typescript function?

Is there a way to create a function that accepts an optional object argument using destructuring in Typescript? myFunction({opt1, opt2}?: {opt1?: boolean, opt2?: boolean}) The error message "A binding pattern parameter cannot be optional in an implementa ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

Error in Typescript: Using forEach method - 'string' type cannot be assigned to 'never' type

I encountered an issue with this code where it's giving me an error message "Type 'string' is not assignable to type 'never'" at the specified comment. type serviceInfoType = { PORT: number; HOST: string; MS_NAME: strin ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

What is the best way to handle API requests within an Angular component?

I am currently diving into the world of Angular at my workplace, even though I do not have a background in web development. One challenge I am facing is how to encapsulate API calls within one of my components without knowing where to begin. The componen ...

I'm having trouble setting a value for an object with a generic type

I am attempting to set a value for the property of an object with generic typing passed into a function. The structure of the object is not known beforehand, and the function receives the property name dynamically as a string argument. TypeScript is genera ...

Hide the FormArray in a Reactive Form if it is not populated or cannot be determined

As a newcomer to Angular 4, I've embarked on my first project and started learning the ropes. I have devised a Reactive Form to showcase a form structure that looks like this: Form (FormGroup) | --> aggLevels (FormArray) | --> ...

Using Angular to transform a JSON GET response into a class with methods

Essentially, I am working with an Angular component that has a variable called DashboardConfiguration which is set to an Observable. This Observable is obtained from a resolver that utilizes a service to make a GET request for a JSON object. The issue lie ...

Streamlined Authorization in MEAN (SPA) Applications

I have created an application, but now I am trying to adapt it into a SPA application. The main issue I am facing is with the Authorization process. While I can successfully register new users, log them in, and retrieve their tokens, I seem to encounter a ...

Sending data to a parent component from a popup window in Angular Material using a button click while the window is still open

How can I retrieve data from an Angular Material Dialog Box and send it to the Parent component? I am able to access data after the dialog box is closed. However, I am wondering if there is a way to retrieve data while the dialog box is still open, especi ...

Is the parameter rejecting the use of orderBy for 'startTime'?

Hey there! I'm currently working on an AngularJS project in TypeScript that involves integrating Google API to fetch Google Calendar events. The syntax for making a call is specified in the documentation available at: https://developers.google.com/goo ...

Alter the attributes of an instance in a class using a function

Attempting to explain a simple method in TypeScript. This method should allow modification of data for any object type within the data attribute. In simpler terms, we can modify, add, or remove data based on the specified data type, and TypeScript facilit ...

Exploring directory organization in GraphQL Queries using GatsbyJS

In my portfolio, I have organized my work into categories, pieces, and pictures in a cascading order similar to a child-parent relationship. The folder structure reflects this hierarchy, with the main problem being explained in more detail below. Folder s ...