Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds.

Currently, I have a function that returns a Promise, but I need it to return the outcome of that Promise:

public static getWifiInfos(): Observable<Promise<ConnectionInfo>> {
    return Observable
        .interval(3000)
        .map(() => Hotspot.getConnectionInfo());
}

Any suggestions on how to achieve this desired functionality?

Answer №1

To solve your problem, you should utilize the switchMap function, which links an interval to the results of a different Observable. It's difficult to explain it in any other way.

public static fetchWirelessDetails(): Observable<ConnectionInfo> {
  return <Observable<ConnectionInfo>> Observable
    .interval(3000)
    .switchMap(() => 
      Observable.fromPromise(Wifi.getConnectionInfo())
    )
}

Answer №2

Here is a suggestion for you to try:

private connectionInfoSubject = new Subject<ConnectionInfo>();

connectionInfoObservable = this.connectionInfoSubject.asObservable();

public static getWifiInfos(): Observable<ConnectionInfo>{
    Observable
        .interval(3000)
        .map(() => {
            // Assuming Hotspot.getConnectionInfo is a synchronous call                
            this.connectionInfoSubject.next(Hotspot.getConnectionInfo());
            // If Hotspot.getConnectionInfo returns a promise
            Hotspot.getConnectionInfo().then(result => {
                this.connectionInfoSubject.next(result);
            })
        });
}

I hope this information proves helpful!

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

Trigger @HostListener event after a certain delay

I am currently working on implementing a basic infinite-scroll directive in Angular2. To achieve this, I am utilizing @HostListener('window:scroll') to capture the scroll event and extract the data from the $target. My concern is that every time ...

How to access the audio element in Angular using ViewChild: Can it be treated as an

My goal is to include an audio element inside a component. Initially, I approached this by using traditional methods: $player: HTMLAudioElement; ... ngOnInit() { this.$player = document.getElementById('stream') } However, I wanted to follow T ...

What is the process for importing types from the `material-ui` library?

I am currently developing a react application using material-ui with typescript. I'm on the lookout for all the type definitions for the material component. Despite attempting to install @types/material-ui, I haven't had much success. Take a look ...

Sharing packages within nested scopes

Using @organization-scope/package/sub-package in npm is what I want to achieve. Here is my package.json configuration:- { "name": "@once/ui", ... ... } If I try the following:- { "name": "@once/ui/select-box", ... ... } An error pops up st ...

Vercel deployment encountered an AxiosError with a status code of 404

I am currently working on an API route called app/api/posts/route.ts, which is responsible for fetching all posts from my database using Prisma ORM. In the localhost environment, the database is hosted on my local PostgreSQL server. However, in production, ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...

Maintaining ongoing subscriptions using rxjs in Angular 5

As a newcomer to rxjs in Angular 5, I find it a bit challenging to articulate my question, but I am hopeful for some guidance. I frequently encounter the same setup: Multiple Components to display identical data A single Service for accessing the data ...

What are some effective methods for troubleshooting Vue.js computed properties and templates?

I am facing challenges with debugging in Vue.js, especially when it comes to debugging computed properties or data values in templates. Currently, I am using the IIFE method for debugging as shown in : <h2 dir="auto"> {{(function(){debugger;let ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...

Do changes in Input fields reflect in the parent component?

I was under the impression that I could share data with child components using @Input() directive and communicate data back to the parent component with @Output() along with the appropriate emit. However, I recently discovered that modifications made to th ...

Having trouble grasping the concept of Interfaces and dealing with FormGroup problems in Angular?

Apologies if my question is a duplicate, I have found several solutions for the same issue on Stack Overflow, but unfortunately, I struggle to understand them in technical terms. Problem 1 src/app/models/dataModel.ts:2:5 2 id: number; ~~ The exp ...

Discovering the RootState type dynamically within redux toolkit using the makeStore function

I am currently working on obtaining the type of my redux store to define the RootState type. Previously, I was just creating and exporting a store instance following the instructions in the redux toolkit documentation without encountering any issues. Howev ...

The process of setting up a dynamic cursor in ReactFlow with Liveblocks for precise zooming, panning, and compatibility with various screen resolutions

The challenge lies in accurately representing the live cursor's position on other users' screens, which is affected by differences in screen resolutions, zoom levels, and ReactFlow element positioning as a result of individual user interactions. ...

Alert: TypeScript Linter Warning

When I execute the npm lint command in Circle CI, a warning message is displayed. The following rules specified in the configuration could not be found: templates-use-public no-access-missing-member invoke-injectable template-to-ng-templa ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Getting Typescript Compiler to Recognize Global Types: Tips and Strategies

In the top level of my project, I have defined some global interfaces as shown below: globaltypes.ts declare global { my_interface { name:string } } However, when attempting to compile with ts-node, the compiler fails and displays the er ...

How can I set up BaconJS in conjunction with Webpack and CoffeeScript?

Currently in the process of transitioning old code to Webpack and encountering some issues... Utilizing a dependency loader in TypeScript import "baconjs/dist/Bacon.js" And a module in CoffeeScript @stream = new Bacon.Bus() Upon running the code, I en ...

Strategies for steering clear of god components in Angular

Currently, I am delving into Angular and following the traditional approach of separating the template, styles, and component into 3 distinct files. The component file houses various functions that serve different purposes: Some functions are activated b ...

Can a universal type be designed for application across various types?

I've got this function: function stackPlayer(stack){ } The stack parameter can have one of the following forms only: a function that takes req, res, and next as arguments. a function that takes req, res, and next as arguments, and returns a functio ...

What could be causing the malfunction of the constructor of these two root services?

Below are two primary root services: Service 1: @Injectable({ providedIn: 'root', }) export class DataService { private data$ = new BehaviorSubject([]); public dataObs$ = this.data$.asObservable(); constructor(private http: HttpClient) ...