Sign up for an observable property that is initially empty

I'm currently working with rxjs in combination with Angular.

Within my codebase, I have a class that includes a public property which is of type observable.

Another class within the application needs to subscribe to this particular observable.

The issue arises when the observable starts off as null and is only initialized after a slight delay.

To temporarily address this problem, I resorted to using an unsightly setTimeout function.

What are some cleaner solutions that can be implemented?

class HasAnObservable {
      observableProp: Observable<any> = null;
      constructor() {
            // This method is responsible for initializing the Observable
            this.initObservableProp();
}

class UsesTheObservable {
     constructor(private readonly hasAnObservable: HasAnObservable) 
     {
         this._useTheObservable()
     }

     private _useTheObservable() {
          // The main issue lies in the fact that observableProp begins as null
          this.hasAnObservable.observableProp.subscribe()
     }
}

Answer №1

Your instance is somewhat confusing in relation to the correct usage of Observables. It is possible to initiate an Observable at any time, but you may not want it to emit any values:

class HasAnObservable {
      private observableSource: ReplaySubject<any>;
      observableProp: Observable<any>;

      constructor() {
          this.observableSource = new ReplaySubject();
          this.observableProp = this.observableSource.asObservable();

          // a function that takes time to produce the initial value
          setTimeout(() => {
              this.observableSource.next('foobar');
          }, 1000)
      }
}

In this scenario, observableProp is set up right away in the constructor, allowing for immediate subscription. However, the initial value will be delayed due to the lengthy initialization process.

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

Unable to receive FCM Push Notifications for web when testing on local server

I am currently working on implementing web push notifications in our web app. I have successfully set up Firebase Cloud Messaging in my app by following the documentation. I am able to prompt the user for permission to receive notifications and obtain the ...

What are some strategies for distinguishing between callable and newable types?

I seem to be facing a challenge related to narrowing, specifically the differentiation between Fnc (callable) and Class (newable). The code snippet provided functions in Playground, but the autocomplete feature is lacking, as shown in the first image. My ...

Angular 9 ensures that the component template is validated and loaded before the constructor logic is executed

Recently switched from Angular 8 to Angular 9 (without IVY) and encountered some unusual errors indicating that services injected in components are undefined in getters. Upon investigation, I discovered that the getter is being called before the constructo ...

The error message states that the type '{}' does not contain the property 'API_BASE_URL'

Encountering this error message when trying to access my API_URL as defined in the enviroment.ts file within a service class. Error: src/app/product/product.service.ts:12:25 - error TS2339: Property 'API_BASE_URL' does not exist on type '{} ...

Encountering a connection issue with mongoose while using Webpack

Ever since today, I've been encountering an issue when trying to establish a connection to MongoDB using Mongoose within my Next.js application. The error message I'm getting is as follows. Can anyone provide some guidance on how to resolve this? ...

Challenges with Typescript Integration in Visual Studio 2013

Currently diving into typescript as a newbie while going through the Angular tutorial using Visual Studio 2013 for work, which is also new to me. The frustrating part is that Visual Studio seems to be assuming I am going to use a different language (judgin ...

Guide on initiating document-wide events using Jasmine tests in Angular 2/4

As stated in the Angular Testing guidelines, triggering events from tests requires using the triggerEventHandler() method on the debug element. This method accepts the event name and the object. It is effective when adding events with HostListener, such as ...

Utilize the parameter to reach a pre-established offspring

Below, I am attempting to use the parameter ('selected') to invoke a set style function with the passed string parameter (onClick('firstheader')) I hope my point was explained clearly. @ViewChild('firstheader', { static: f ...

Binding two objects to a single event using Angular 2 syntax

Is there a way to connect two simple input fields to a single click event in Angular? One box for typing text and the other providing a timestamp from Date();. How can I show both values when clicking on the button? // The #date input field provides the ...

What are some ways I can implement timers and promises from Node 16 into a Typescript application?

The recent Node 16 release introduces a new timers/promises API that has caught my interest. I successfully installed Node 16 using NVM and switched to it: $ nvm use Found '/Users/golergka/Projects/my-project/.nvmrc' with version <16> ...

The Main Page is always the default destination when navigating with Angular Router

Having an issue with Angular Router (Angular 11). Here is my routing configuration: {path: '', redirectTo: '/login', pathMatch: 'full'} {path: 'login', component: LoginComponent} {path: 'verdicts', componen ...

What is the best way to show specific links in the navigation bar only when the user is signed in using Angular?

I'm attempting to customize the navigation bar to display "Sign In" and "Sign Up" buttons only when the user is not signed in, and show the message and profile navigation items when the user is signed in. Below is the provided code snippet: Token Se ...

Here is the revised text: "What is the best way to send a variable to a component and retrieve it within the ng-template using

I've developed a component named "foo" that accepts a data object and displays it within an ng-template as its own variable. The issue arises when the variable inside the ng-template is of type any, lacking proper typing for checking and autocomplete ...

Checking the loaded status of an observable in Angular

When calling an observable that takes some time to resolve, I found myself needing to add a condition to check for a valid result. The current implementation seems functional, but I can't help feeling there might be a better way to handle this. Here& ...

Ionic 2 encountered an error: A non-empty string argument was anticipated

My goal is to show markers on a map using the stored postcode in JSON format. I have successfully accessed the lat and long values from the JSON data to display markers on the map. However, when I attempt to use the postcode, it fails and returns an erro ...

Typescript is unable to locate an interface when it is stored in a separate directory

I have 2 main folders within my project structure: src/*.ts test/*.test.ts Within the src folder, there exists an interface named IImportRow.ts interface IImportRow { transactionId?: string; transactionApiId?: string; ... } This same inter ...

Is there a way to retrieve the modal's viewport height in Angular?

Is it possible to determine the viewport height of my ng bootstrap modal within my Angular application? Here is what I currently have: I have a modal with CSS styling as shown below: .modal-xxl { width: 95% !important; max-height: 90% !important; ...

The compatibility issue between Tailwind CSS and Material UI has been identified in the latest version of Next, version 14.0

Currently, I am working with Next 14.0.2 alongside Material UI and Tailwind CSS for my Frontend development tasks. However, I've run into some challenges regarding styling components. One specific issue I faced was when setting a button to navigate to ...

What distinguishes ReadonlyArray from the declaration "readonly arr: T[]"?

Check out this unique playground. interface Feature { readonly name: string; } // <Test> // This is OK interface Foo1 { readonly arr: ReadonlyArray<Feature>; } function save1(foo: Foo1) { console.log(foo); } // </Test> // <Tes ...

Loading dynamic content within Angular Material tabs allows for a more customized and interactive user experience

I am currently working on creating a dynamic tab system using Angular Material: Tabs. I have encountered an issue with loading content on tabs after the initial one, where the functionality only works when the first tab is loaded. Below you can see the ta ...