[Fixed] How to signal a BehaviorSubject that the stream is completed

Issue

In angular 2, mySubject (see code) compiles a complete() function, but it errors during execution saying there is no such function. I was unable to get onComplete() to compile.

    import { Component, OnInit } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import * as Rx from "rxjs";
    import {BehaviorSubject} from 'rxjs/BehaviorSubject';

    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })    
    export class HomeComponent {
      myBehavior: any;
      mySubject: BehaviorSubject<string>;
      received = "nothing";
      chatter: string[];
      nxtChatter = 0;
      constructor() {
        this.myBehavior = new BehaviorSubject<string>("Behavior Subject Started");
        this.chatter = [
          "Four", "score", "and", "seven", "years", "ago"
      ]        
    }        

      Start() {
        this.mySubject = this.myBehavior.subscribe(
          (x) => { this.received = x;},
          (err) => { this.received = "Error: " + err; },
          () => { this.received = "Completed ... bye"; }
        );
    }         

      Send() {
        this.mySubject.next(this.chatter[this.nxtChatter++]);
        if (this.nxtChatter >= this.chatter.length) {
           this.nxtChatter = 0;
           this.mySubject.complete();
        }    
       }    
    }        

Solution

This line:

this.mySubject = this.myBehavior.subscribe(

returns a subscription object, not the subject. And subscription doesn’t have a complete or next function. To trigger complete on the subject do the following:

this.myBehavior.complete();

And also here you’re triggering next on subscription:

this.mySubject.next(this.chatter[this.nxtChatter++]);

You need to trigger it on the subject:

this.myBehavior.next(this.chatter[this.nxtChatter++]);

To learn more about BehaviorSubject see this resource.

Leave a Reply

(*) Required, Your email will not be published