rxjs icon indicating copy to clipboard operation
rxjs copied to clipboard

cache(), share(), publish().refCount() and publishReplay().refCount() do not work as told

Open jvanbruegge opened this issue 10 years ago • 5 comments

Hi, I'm fairly new to RxJS, so this could be a misunderstanding, but for the following situation: I have a Service singleton that queries a REST API, like this:

export class Service
{
  public get RestStream() : Observable<RestModel> { 
    return this.getStuff().publishReplay().refCount(); 
  }
...
}

"this.getStuff()" queries the API and returns an Observable In my understanding, every further transformation of the RestStream in other classes shouldnt requery the API, because I cached it (Say for example I want a part of the RestModel and add a function somewhere that returns service.RestStream.map(<something>)). So any subscribtion to the service or depenent services that further transform the Observable should not requery to API. I guess this is wrong, because I get plenty of requests in chrome to an url that is only requested in that getStuff() method. What is the correct way to implement the behavior that I want? (I already tried the operators in the heading)

jvanbruegge avatar Mar 01 '16 14:03 jvanbruegge

I'm still new to typescript, but I have a feeling that it's because every time you call the getter, it creates a new observable. Try something like this?

export class Service {
    private _restStream: Observable<RestModel>;

    public get RestStream(): Observable<RestModel> {
        return this._restStream;
    }

    constructor() {
        this._restStream = this.getStuff().publishReplay().refCount();
    }
}

tariqkb avatar Mar 01 '16 16:03 tariqkb

@SuperManitu I have to say that @tbugrara is right on.

Think of an Observable like a function. In this case, it's a function that starts a request the first time it's called (subscribed to) and shares that request (or it's result) with everyone else that calls it (subscribes to it).

@tbugrara's example is exactly right. Also in beta.2 you can replace .publishReplay().refCount() with .cache() as they are the same.

benlesh avatar Mar 01 '16 16:03 benlesh

Closing this for now, as it's been answered, feel free to reopen if you think there is an actual bug or issue with the library to be addressed.

benlesh avatar Mar 01 '16 16:03 benlesh

I have to reopen, because that was what I tried in the first place, saving getStuff().cache() to a global variable, but that didnt word either

jvanbruegge avatar Mar 01 '16 17:03 jvanbruegge

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Jun 07 '18 10:06 lock[bot]