Ka Tech Ka Tech - 2 years ago 215
AngularJS Question

AngularJs - RXJS Observable unsubscribe

I have setup an RXJS observable. I have two components which subscribe to a subject in service factory. How do I unsubscribe a selected component to the subject so that a button is pressed it stops listening to the subject broadcast?

See my jsfiddle Unsubscribe App

My code:

<div ng-app="myApp" ng-controller="mainCtrl">

<script type="text/ng-template" id="/boxa">
BoxA - Message Listener: </br>
<md-button ng-click='boxA.unsubcribe()' class='md-warn'>Unsubscribe A</md-button>
<script type="text/ng-template" id="/boxb">
BoxB - Message Listener: </br>
<md-button ng-click='boxB.unsubcribe()' class='md-warn'>Unsubscribe B</md-button>

<md-content class='md-padding'>
<label>Enter Text To Broadcast</label>
<input ng-model='msg'/></br>
<md-button class='md-primary' ng-click='broadcastFn()'>Broadcast</md-button></br>

</div><!--end app-->

var app = angular.module('myApp', ['ngMaterial']);
app.controller('mainCtrl', function($scope,msgService) {

$scope.name = "Observer App Example";
$scope.msg = 'Message';
$scope.broadcastFn = function(){

app.component("boxA", {
bindings: {},
controller: function(msgService) {
var boxA = this;
boxA.msgService = msgService;
boxA.msg = '';
boxA.msgService.subscribe(function(obj) {
console.log('Listerner A');
boxA.msg = obj;


controllerAs: 'boxA',
templateUrl: "/boxa"
app.component("boxB", {
bindings: {},
controller: function(msgService) {
var boxB = this;
boxB.msgService = msgService;
boxB.msg = '';
boxB.msgService.subscribe(function(obj) {
console.log('Listerner B');
boxB.msg = obj;


controllerAs: 'boxB',
templateUrl: "/boxb"

app.factory('msgService', ['$http', function($http){
var msgSubject = new Rx.ReplaySubject();

Answer Source

Please see updated fiddle: here

the subscribe function returns a Disposable to work with and you must first return the subscription from your factory (line 60):

subscribe: function(subscription){
    return msgSubject.subscribe(subscription);

This will let you store your subscription in each controller to work with in the future. (line 21 & 42)

var boxASubscription = boxA.msgService.subscribe(function(obj) {
    console.log('Listerner A');
    boxA.msg = obj;

You can then call the dispose method on the subscription when you want to unsubscribe:

boxA.unsubscribe = function(){
    console.log('Unsubscribe A');


For some reason I couldn't get your demo to work with <md-button> so I changed this to <button> for the sake of the demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download