Building a BaseObserver in TypeScript with RxJS

Initially, I created a class called BaseObserver in Swift. In the subscribe method, I pass this class. Now, I am attempting to achieve the same functionality in RxJS using TypeScript.

This approach proves useful when you need to execute actions both before and after certain events.

import Foundation
import RxSwift

class BaseObserver<Element>: ObserverType {

    public typealias E = Element

    var beforeClosure: (() -> Void)?
    var completeClosure: ((E) -> Void)?
    var errorClosure: ((Error) -> Void)?
    var completedClosure: (() -> Void)?
    var alwaysClosure: (()->())?
    var onCompleteOrError: ((Error?) -> Void)?

    init(beforeComplete: (() -> Void)? = nil, onComplete: ((E) -> Void)? = nil, onError: ((Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, always: (()->())? = nil, onCompleteOrError: ((Error?) -> Void)? = nil) {
        self.alwaysClosure = always
        self.completeClosure = onComplete
        self.errorClosure = onError
        self.completedClosure = onCompleted
        self.beforeClosure = beforeComplete
        self.onCompleteOrError = onCompleteOrError
    }

    func on(_ event: Event<Element>) {
        switch event {
        case .next(let element):
            beforeClosure?()
            completeClosure?(element)
        case .error(let error):
            beforeClosure?()
            errorClosure?(error)
            onCompleteOrError?(error)
        case .completed:
            completedClosure?()
            onCompleteOrError?(nil)
        }
        alwaysClosure?()
    }
}

Answer №1

class CustomObserver implements Observer<any> {
  constructor(
    private funcBefore,
    private funcAfter) {
  }

  next = (value: any) => {
    this.funcBefore(value)
    this.funcAfter(value)
  };
  error = (err: any) => {};
  complete = () => {};
}

const logBefore = value => {
  console.log('before', value)
}
const logAfter = value => {
  console.log('after', value)
}

const customObserver = new CustomObserver(logBefore, logAfter);

const dataStream = of(1, 2, 3)
const subscription = dataStream.subscribe(this.customObserver);

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

Data binding in Angular 2: Connecting components

Is it possible to establish a connection between two components that are working with related objects? One of the components is dedicated to filtering, while the other displays the data results. By applying filters such as checkboxes, the displayed data ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

One way to update the value of the current array or object using ngModel in Angular 2 is to directly

I have a situation where I am dealing with both an array and an object. The array is populated with data retrieved from a service, while the object contains the first element of that array. feesEntries: Array<any> = []; selectedFeesEntry: any; clien ...

I noticed that when using Next.js with the `revalidate: 1` option on a static page, it is triggering two full F5 refresh actions instead of just one. I was hoping for

Currently, I have set up a blog post edit page in my Next.js project. The post pages are utilizing the Incremental Static Regeneration feature with a revalidation time of 1 second for testing purposes. In the future, I plan to increase this to a revalidat ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

The object must contain a property 'children', which is required in the type '{ children: any; }' but missing in the type '{}'

While learning React from a variety of sources, I've encountered an issue with one of the examples. Error message: Property 'children' is missing in type '{}' but required in type '{ children: any; }' export default fu ...

Transferring data from child to parent components in React

Having trouble connecting my parent component, a Search widget, with Filters from a separate Drawer component. The user input triggers an API call and the results need to be filtered based on selectors from the drawer. Can't seem to establish the link ...

Triggering an event from a higher-level component to a lower-level component

Within the parent component named personDetails, there is a Submit button. This parent component contains multiple child components called person`. Each time I click on the Submit button, I need to trigger a method within the child component. Is it possib ...

Troubleshooting: Issues with Angular2 compatibility on Safari version 9.1.2

I am encountering an issue with running my angular2 app on Safari 9.1.2. It works fine on all higher versions of Safari as well as other browsers such as Chrome, Firefox, Opera, and Edge. However, when I try to run it on Safari 9.1.2, I receive the followi ...

Unit test: Using subjects instead of observables to mock a service and test the change of values over time results in TypeScript throwing error TS2339

I have a unique scenario where I have implemented a service that accesses ngrx selectors and a component that utilizes this service by injecting it and adjusting properties based on the values retrieved. For unit testing purposes, I am creating mock versi ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

Ways to insert script tag in a React/JSX document?

private get mouseGestureSettingView() { const {selectedMenu} = this.state; return ( selectedMenu == 2 ? <script src="../../assets/js/extensions/mouse-gesture/options.js"></script> <div className={styles.settingForm}& ...

Utilize multiple activated modules in Angular 2

Recently, I've been exploring the new features of Angular 2 final release, particularly the updated router functionality. An interesting example showcasing the router in action can be found at this link: http://plnkr.co/edit/mXSjnUtN7CM6ZqtOicE2?p=pr ...

How can I access the parameter value for the tooltip callback function within echarts?

I am attempting to retrieve the value for this specific Apache EChart from within the callback function of the tooltip formatter. When I manually input the value, the formatting function operates correctly: formatter: (params:any) => `$ ${Math.round(pa ...

How should we correctly import jquery.inputmask?

Struggling to import jquery.inputmask using webpack and TypeScript? Head over to this discussion at Issue #1115 : Here's how I configured things with jqlite: To import in your app, use the following code: import InputMask from 'inputmask&apos ...

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...

What is the proper method for utilizing a conditional header in an rtk query?

How can I implement conditional header authentication using rtk query? I need to pass headers for all requests except refresh token, where headers should be empty. Is it possible to achieve this by setting a condition or using two separate fetchBaseQuery ...

Transform ECMAScript Observable / Zen Observable into RXJS Observable

I currently have an ECMAScript Observable that is compliant with specifications, specifically sourced from the wonka library. I am facing challenges in converting this type of observable to an rxjs 6 observable. It appears that this conversion was possibl ...