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 possible with rxjs 5. I attempted the following:

import { pipe, toObservable, fromArray } from 'wonka';
import { from } from 'rxjs';
...
from(
  pipe(
    fromArray([1, 2, 3]),
    toObservable
  )
);

Upon testing this code in the browser, I encountered this error message:

ERROR TypeError: You provided an invalid object where a stream was expected.
You can provide an Observable, Promise, Array, or Iterable.

and also received this error:

Argument of type 'observableT<any>' is not assignable to parameter of type 'ObservableInput<any>'

In order to work around this issue, I managed to convert it to a zen-observable by following these steps:

npm i zen-observable
npm i --save-dev @types/zen-observable
import { from } from 'zen-observable';
...
getObservable(): Observable<any> {
  return from(
    pipe(
      fromArray([1, 2, 3]),
      toObservable
    ) as any) as any;
}

However, utilizing a zen-observable does not offer the same capabilities and functionalities as an rxjs observable.

If you have insights on how to properly convert this to an rxjs observable, I would greatly appreciate your help.

Thank you, J

Answer №1

Create a conversion method that leverages the similarity in subscription APIs:

function convertZenToRx<T>(zenObservable: Zen.Observable<T>): Rx.Observable<T> {
  return new Rx.Observable(
    observer => zenObservable.subscribe(observer)
  );
}

Answer №2

After tweaking backtick's solution, I finally made it functional:

return new Observable((observer: any) => {
  pipe(
    fromArray([1, 2, 3]),
    toObservable
  ).subscribe(observer);
});

Answer №3

Unfortunately, none of the solutions provided up to 08 Jun 2023 seemed to work for my specific case.

In response, I took matters into my own hands and crafted a custom injectable service class.

Check out the code snippet below:

// Class: CustomConverterService (injectable service)
// Author: [Your Name]
// Date: [Current Date]
//
// Description: This service is designed to convert a Zen Observable to an Rx
// Observable, allowing you to leverage the powerful features that Rx offers.
// By mirroring Zen Observable events onto an Rx Observable using Subjects,
// we can seamlessly integrate the two frameworks.
//
// The resulting Subject<T> can be used as either an Rx Observable<T>
// or Rx Subject<T>, depending on your preference.
//
// One key advantage of using Rx Observables/Subjects over Zen Observables
// is the ability to utilize Rx pipes and utilities like @ngneat/until-destroy
// for automatic subscription cleanup.
//
// Note that our custom Zen subscription is automatically unsubscribed when
// the Subject<T> is unsubscribed or terminated.
//
// Remember to manage the subscriptions obtained from the returned Subject<T> object.
//
// For usage in Angular components, ensure you are familiar with injecting services.
//
import { Injectable } from '@angular/core';
import { Subject, finalize } from 'rxjs';
import { Observable } from 'zen-observable-ts';

@Injectable({
  providedIn: 'root',
})
export class CustomConverterService {
  convertZenObservable<T>(zenObservable: Observable<T>): Subject<T> {
    const subject = new Subject<T>();
    const zenSubscription = zenObservable.subscribe((e: T) => subject.next(e));

    return subject.pipe(
      finalize(() => {
        zenSubscription.unsubscribe();
        console.log('Zen subscription successfully unsubscribed!');
      })
    ) as Subject<T>;
  }
}

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 attribute 'randomUUID' is not found within the 'Crypto' interface

I attempted to utilize the crypto.randomUUID function in my Angular app version 13.1, however, it does not seem to be accessible. When trying to use it, I encountered this error: TS2339: Property 'randomUUID' does not exist on type 'Crypto ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

Unable to access 'this' within a custom operator in RxJs

I developed a unique operator that utilizes the this keyword, but I am encountering an issue where it always returns undefined. Even though I used bind to pass this into the function. My special operator function shouldLoadNewOptimizationData() { retu ...

Transform the `PascalCase` format into `strictCamelCase` in TypeScript type conversion

By utilizing the built-in Uncapitalize<S> function, you can easily convert a string like FooBar to fooBar: const fooBar: Uncapitalize<'FooBar'> = 'fooBar'; However, this method proves inadequate when dealing with class name ...

Ensure that enums in Typescript are initialized explicitly

Is there a way to explicitly initialize the following enum in typescript? enum BloodGroup { OPositive = "O +ve", ONegative = "O -ve", APositive = "A +ve", ANegative = "A -ve", } I attempted something like this (I know it won't wo ...

Is there a way to transfer data to a different component in React without relying on a hierarchical parent-child relationship?

I am struggling to pass the data from the "SearchingData" Component to the "Search" Component. The SearchingData component is a child of the Search component. I need to transfer the data from the variable named "datacame" to the Search Component. Can som ...

What triggers the execution of the catch method while chaining HTTP promises?

In my Angular application, I have developed a custom loaderService that displays a loading spinner while the back-end processes requests. Below is the code snippet: export class ComponentOne { constructor(loaderService: LoaderService, orderService: Orde ...

Sending a parameter to a confidential npm module

I've developed a custom npm module that can be used in my applications by including this code snippet in the HTML: <app-header-name></app-header-name> Here is the TypeScript code inside the npm package: import { Component, OnInit } from & ...

Expanding the Warnings of React.Component

When I create a new class by extending React.Component in the following manner: export default class App extends React.Component<any, any > { constructor (props: React.ReactPropTypes) { super(props); } // other code } I encountere ...

Modify the property of the ChildComponent by utilizing the ViewChild method

I recently started exploring Angular and I've been experimenting with ViewChild and ViewChildren. In one scenario, I have a property called today = new Date() in my Component2. I'm accessing this property in Component1 using ViewChild and continu ...

Steps for updating the value of a button in Typescript and React

I currently have a button that manages my language switcher, configured to handle cookies, URL changes, and now I want it to update the translations on the page as well. The <img> tag is utilized for changing the country flag. < ...

Angular Protectors: Stop unauthorized access to a URL while allowing authorized refresh

I've developed a Protection feature that blocks users from directly accessing a specific URL, and it's functioning correctly. However, the issue arises when I try to refresh the page as the Protection feature ends up redirecting me. Below is th ...

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

Transform the date format in react.js using information provided by an API endpoint

I'm currently working on a project using React and TypeScript where I need to format the date retrieved from an API. I am able to map over the data and display it, but I'm struggling to convert it into a format like '22 June 2021'. The ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Angular 8 HTTP Interceptor causing issues with subscriptions

I'm currently in the process of setting up an Angular 8 project that will allow me to mock API calls using HTTP INTERCEPTORS. My approach involves adding a --configuration=mock flag to my ng serve script so that the interceptor is injected into my app ...

typescript what type of functionality do dynamic class methods provide

I'm currently working on building a class that creates dynamic methods during the constructor stage. While everything is functioning properly, I've encountered an issue with VS Code's auto suggestion not recognizing these dynamic methods. Ho ...

Why is my Angular Reactive form not retrieving the value from a hidden field?

I've encountered a problem where the hidden field in my form is not capturing the product id unless I manually type or change its value. It consistently shows as "none" when submitting the form. TS https://i.stack.imgur.com/W9aIm.png HTML https://i. ...

The continuous rerendering of my component occurs when I use a path parameter

In my project, I am working on utilizing a path parameter as an ID to fetch data for a specific entity. To accomplish this, I have developed a custom data fetching hook that triggers whenever there is a change in the passed parameters. For obtaining the bo ...

Tips for determining if an array of objects, into which I am adding objects, contains a particular key value present in a different array of objects

I've been working on this and here is what I have tried so far: groceryList = []; ngOnInit() { this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => { this.loadedRecipes = receivedData.recipes; }); } onCheckRecipe(e) { ...