3

I have this code that grabs a cached value:

getConfigurations(): Observable<SiteConfiguration[]> {
    return this.storageService.getSiteConfigurations().map(c => {
        if(c) {
            return c;
        }                         
        return this.httpClient.get<SiteConfiguration[]>(this.url + "/config").subscribe(c => c);
    });        
}

I cache the SiteConfiguration object, but need to go to the server to get it if it doesn't exist. But I can't return the second observable inside the first, as it would be returning an Observable<Observable<SiteConfiguration[]>>.

I'm sure this is a common scenario but my google-fu failed to find an answer.

2

1 Answer 1

7

your code should look like this

getConfigurations(): Observable<SiteConfiguration[]> {
    return this.storageService.getSiteConfigurations().flatMap(c => {
        if(c) {
            return Obserbable.of(c);
        }                         
        return this.httpClient.get<SiteConfiguration[]>(this.url + "/config")
    })        
}



getCOnfiguration().subscribe(c => c);
Sign up to request clarification or add additional context in comments.

2 Comments

great! thanks. I had seen flatMap but didn't know the use of it. After seeing your code it seems pretty obvious
just take your time to read about Observables and rxjs , is crazy the thinks you can do with that library

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.