1
votes

I'm developing an angular 5 application where I have an Observable like this one:

Observable.interval(10000)
    .takeWhile(() => !this.zeServerIsOnline)
    .subscribe(i => { 
        this.systemService.isServerOnline().subscribe(data => {
            if(data.success) {
                this.zeServerIsOnline = true;
                this.serverPolledForState = false;
                if(this.bookingsInStorage > 0) {
                    this.allBookingsSubmitted = false;
                    this.sendSavedBookingsToServer();
                }
            }
        }, error => this.isServerOnlineFailed(error));
    });

i first thought, that the observable gets directly unsubscribed, when my Boolean this.zeServerIsOnline gets true but it gets unsubscribed, when again 10 seconds are over and the observable recognizes the state of my Boolean (this.zeServerIsOnline) is true than.

So if i now recognize, that my server is online again (this.zeServerIsOnline = true), i'm starting transmitting data (and i thought that this is the place, when the observable is unsubscribed) But now, when the server goes offline again while i'm transmitting data and 10 seconds are not over my Observable triggers again because it didn't recognize the switch from false to true to false.

Only when my server is online longer than 10 seconds, my observable gets unsubscribed. So it must have sth. to do with the interval but how do i directly unsubscribe, when this.zeServerIsOnline gets true?

1

1 Answers

1
votes

Create a variable type of ISubscription

subscription: ISubscription;

Let's think you need to unsubscribe this.systemService.isServerOnline(). You could do it like:

this.subscription = this.systemService.isServerOnline().subscribe(data => {
            if(data.success) {
                this.zeServerIsOnline = true;
                this.serverPolledForState = false;
                if(this.bookingsInStorage > 0) {
                    this.allBookingsSubmitted = false;
                    this.sendSavedBookingsToServer();
                }
            }
        }, error => this.isServerOnlineFailed(error));

Or if you need to unsubscribe Observable.interval(10000) you could do it like:

this.subscription = Observable.interval(10000)
      .takeWhile(() => !this.zeServerIsOnline)
      .subscribe(i => {
        this.systemService.isServerOnline().subscribe(data => {
          if (data.success) {
            this.zeServerIsOnline = true;
            this.serverPolledForState = false;
            if (this.bookingsInStorage > 0) {
              this.allBookingsSubmitted = false;
              this.sendSavedBookingsToServer();
            }
          }
        }, error => this.isServerOnlineFailed(error));
      });

And now you could directly unsubscribe it:

this.subscription.unsubscribe();

You can directly unsubscribe what ever subscription in this way.

Hope this will help you!