Haris Bašić
Haris Bašić

Reputation: 1383

Subscribing to existing observable in RxJs

My angular service returns observable. However, whenever I subscribe to it, it is being called all over again. In this particular example, you can see that request for getting users is being sent 10 times instead of once with multiple observers.

Expected behaviour: Create observable and subscribe to it. Only one request is sent and all subscriptions receive the same value.

@Injectable()
class ExampleService {
  constructor(private http: Http) { }
  read() {
    return this.http.get('https://api.github.com/users');
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>

      <button (click)='test()'>Test</button>
    </div>
  `,
})
export class App {
  name:string;
  subscription: Observable<any>;

  constructor(private exampleService: ExampleService) {
    this.name = `Angular! v${VERSION.full}`
  }

  test() {
    for (let x = 0; x < 10; x++) {
      if (this.subscription) {
        console.log('Using existing subscription');

        this.subscription.subscribe(
          response => {
            console.log('From another')
          })
      } else {
        this.subscription = this.exampleService.read();
        this.subscription.subscribe(
          response => {
            console.log('From originalSubscription');
            this.subscription = null;
          });
      }

    }
  }

}

Any help?

Upvotes: 0

Views: 697

Answers (1)

Robin Dijkhof
Robin Dijkhof

Reputation: 19278

Try this:

@Injectable()
class ExampleService {
  constructor(private http: Http) { }
  read() {
    return this.http.get('https://api.github.com/users').publishReplay().refCount();
  }
}

Upvotes: 1

Related Questions