[rxjs] Shares a single subscription -- publish()

If have an observable and you subscribe it twice, those tow subscritions have no connection. 

console.clear();
var Observable = Rx.Observable;
var _id = 1;

var source = Observable.create(function(Observe){
  var myId = _id++;
  Observe.onNext('Observable ' + myId);
  setTimeout(function(){
    Observe.onNext('Observable... ' + myId);
    Observe.onCompleted();
  }, 1000);
});

var subscrition1 = source.subscribe(function onNext(x){
  console.log('Observable 1: ' + x);
});

var subscrition2 = source.subscribe(function onNext(x){
  console.log('Observable 2: ' + x);
});

Result:

/*"Observable 1: Observable 1"
"Observable 2: Observable 2"
"Observable 1: Observable... 1"
"Observable 2: Observable... 2"*/

 

publish():

Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.

console.clear();
var Observable = Rx.Observable;
var _id = 1;

var source = Observable.create(function(Observe){
  var myId = _id++;
  Observe.onNext('Observable ' + myId);
  setTimeout(function(){
    Observe.onNext('Observable... ' + myId);
    Observe.onCompleted();
  }, 1000);
});
var published = source.publish();

var subscrition1 = published.subscribe(function onNext(x){
  console.log('Observable 1: ' + x);
});

var subscrition2 = published.subscribe(function onNext(x){
  console.log('Observable 2: ' + x);
});

var connection = published.connect();

Results:

/*
"Observable 1: Observable 1"
"Observable 2: Observable 1"
"Observable 1: Observable... 1"
"Observable 2: Observable... 1"
*/

You can see the result just have one single subscrition then.

 

You can dispose the connection:

connection.dispose();

Results:

/*"Observable 1: Observable 1"
"Observable 2: Observable 1"*/

 

There is a problem when you connect the published observables at different place.

var Observable = Rx.Observable;
var _id = 1;

var source = Observable.create(function(Observe){
  var myId = _id++;
  Observe.onNext('Observable ' + myId);
  setTimeout(function(){
    Observe.onNext('Observable... ' + myId);
    Observe.onCompleted();
  }, 1000);
});
var published = source.publish();
var connection = published.connect();

var subscrition1 = published.subscribe(function onNext(x){
  console.log('Observable 1: ' + x);
});

var subscrition2 = published.subscribe(function onNext(x){
  console.log('Observable 2: ' + x);
});

//var connection = published.connect();

Results:

/*"Observable 1: Observable... 1"
"Observable 2: Observable... 1"*/

If we move the connect() funciton up before subscribe(). Then we missed the very first console.log(); It means connection is already start, but no one subscribe it yet.

 

Therefore, we don't use publish() funciton alone, more than often we use publish().refCount() function together.

posted @ 2015-08-24 15:45  Zhentiw  阅读(339)  评论(0编辑  收藏  举报