What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below?

const liftFun = fun => {
    try {
        return of(fun())
    } catch (err) {
        return throwError(err)
    }
}

Answer №1

Transforming into observable

 const liftFunction = fn => new Observable(observer => {
        try {
            return observer.next(fn)
        } catch (error) {
            return observer.error(error)
        }
    })

Alternatively, you can convert it into an operator function that can be used in a pipe chain.

const liftFunction = fn => mergeMap(action => {
    try {
        return of(action())
    } catch (error) {
        return throwError(error)
    }
})

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

Extract information from a URL without the need for a page reload or user interaction

Recently, I developed a form that accepts YouTube links and extracts the ID using parsing/regex. The function is triggered by clicking a button, which then displays the ID of the URL. Is there a way to show the ID without requiring a button click or page ...

Options for HTML technologies in an application designed for managing enterprise metadata

Challenge We are facing the decision of determining which technologies to adopt as we transition from a rich client Silverlight application to an HTML-based client that can accommodate a metadata driven approach. Situation Our enterprise has been using ...

Steps to prevent submission of input field until all necessary fields and checkboxes are filled, disabled the submit button

Check out my basic web application on this sandbox link: codesandbox.io/s/eager-kalam-v1lpg I need assistance with how to prevent the submit button from being enabled until all required fields and checkboxes are filled in. I am fairly new to working with ...

Interface of TypeScript Undetermined

Currently, I am developing a Demo API Wrapper specifically for Roblox. During the development process, I have come across a certain issue that I would like to address. My aim is to send a request and then return all the data in the manner of an API wrapper ...

Tips for making a multi-dimensional array using jQuery

Is it possible to generate a jQuery layout by using two separate each statements as shown below? arrar [ 'aaa'=>'ccsdfccc', 'bb'=>'aaddsaaaa', '1'=>[ 'three'=>'sdsds& ...

The importance of .hash in this jquery function explained

I utilized a jQuery function from someone else and tweaked it to fit my needs, however, I am struggling to grasp how it actually operates. Specifically, the line var content = this.hash.replace('/', ''); Can anyone offer an explanation ...

Ensure that only one menu with a specific class is open at any given time

My goal is to ensure that both menus cannot be open simultaneously. The desired behavior is as follows: When one menu is already open and you click on another, the first one should automatically close. For a better understanding of what I am trying to achi ...

What could be the reason for react-query searching for dispatch even when redux is not activated or present in the component?

I am currently working on a component that is supposed to fetch logged-in users from the server. Despite Swagger indicating that the server code returns correctly, the component fails to make the necessary fetch request when loaded. Below is the code snip ...

The JQuery function fails to execute following a successful Ajax request

I recently ran into an issue with my Ajax call. Here's the code snippet in question: $("#start-upload-btn").click(function(){ $.ajax({ type: "post", url: "", data: { newProjectName: $('#project-name') ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Iterate through JSON data and access values based on keys using a $.each loop

I have retrieved JSON data from the controller using AJAX and now I want to access this data. The data is in the form of a list of objects (array) with key-value pairs, so I am planning to use .each() function to go through all the data. The array looks li ...

Selenium Tips: Ensuring RemoteDriver Remains Connected to the Active Browser Tab

Currently working on a unique Windows application that utilizes voice commands to control web browsers. I am trying to figure out the best approach when users add tabs and modify the selected tab as needed. Unfortunately, RemoteDriver only supports swi ...

I am facing an issue with the asynchronous function as it is displaying an error message

**I am facing an issue with displaying categories. I have attempted to do this using async function, however the data is not showing up** <div class="form-group"> <label for="category">Category</label> <select id="categor ...

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the ...

Is my Bootstrap malfunctioning? The grid system seems to be malfunctioning

My very first question here is quite simple. I have a script that creates rows with dynamic content by appending 4 boxes (columns) in one row and then appending the row to the container. After completing this process, it appends the container to the main c ...

The buffer for the operation `users.insertOne()` exceeded the timeout limit of 10000 milliseconds, resulting in a Mongoose

I am currently utilizing a generator that can be found at this Github link Project repository: Github Project Link Encountering an issue when attempting to input a user using the `MASTER_KEY`, I keep receiving the following error message: MongooseError ...

The command "tsc" was not found in this bash session

Currently, I am using a MAC and attempting to set up TypeScript. I followed the installation process by running sudo npm install -g typescript and received the following output: Password: /Users/<myuserid>/node/bin/tsc -> /Users/<myuserid& ...

What could be causing the issue with my Angular integration with Jira Issue Collector to not function properly?

Looking to link the Jira issue collector with an Angular application I attempted something along the lines of Component.ts import { Component, OnInit } from '@angular/core'; import * as jQuery from 'jquery'; declare global { inter ...

Scroll automatically to the following div after a brief break

On my website, the title of each page fills the entire screen before the content appears when you scroll down. I am interested in adding a smooth automatic scroll feature that will transition to the next section after about half a second on the initial "ti ...