Roy Lin
Roy Lin

Reputation: 760

Using an observable to retrieve data over http once, then save the value for reuse

In scala, there is the concept of Futures, where a value gets saved in a future when it becomes ready. And I'm trying to find something similar.

For example, I want access to "user" data. When I first access this, I want to send a request to the server to get the data, but for alls subsequent access, I want to be able to use the stored value.

The following code tries to achieve something similar. It does not guarantee the call to the server will only happen once.

Apologies, the following is in TypeScript:

class AuthenticationService {

  http: Http = Some Http Helper...

  user: Observable<User> = this.http.get("www.example.com/logged-in-user")
    .map(data => {
      let userObject = data.json().user
      this.user = Observable.of(userObject)
      return userObject
    })
}

Is there a better way of doing this?

Upvotes: 0

Views: 938

Answers (1)

acdcjunior
acdcjunior

Reputation: 135822

If I understood correctly, what you are searching for is Rx.BehaviorSubject.

It will store the last value and send to any future subscribers:

import Rx from 'rxjs/Rx'; // just for development, use a more specific when done

class AuthenticationService {

  http: Http = Some Http Helper...

  user: Observable<User> = this.http.get("www.example.com/logged-in-user")
    .map(data => {
      let userObject = data.json().user
      this.user = new Rx.BehaviorSubject(userObject)
      return userObject
    })
}

An example of the functionality alone:

/* Initialize with initial value of 42 */
var subject = new Rx.BehaviorSubject(42);

function subsc(title) {
  subject.subscribe(
    (x) => console.log(title + ' Next: ' + x.toString()),
    (err) => console.log(title + ' Error: ' + err),
    () => console.log(title + ' Completed')
  );
}

subsc("1st"); // Initial Next: 42
subsc("2nd"); // Initial Next: 42

subject.next(56);

subsc("3rd");  // Initial Next: 56

subject.complete();

Upvotes: 2

Related Questions