I'm trying to convert a Peer.JS Peer object into an observable sequence of dataConnections. However, as shown below, the observable of the peer that receives a request for a connection doesn't always emit the dataConnection to its subscriber, even though a connection is always established.
From what I've read, fromEvent() creates hot observables? Is my subscriber missing the dataConnection because it is not subscribing early enough?
import Rx from 'rx';
import Peer from 'peerjs';
import config from '../config';
/**
* Converts a Peer.JS Peer into an Observable sequence of Peer.JS DataConnections
* @param {Peer} [peer] A Peer.js Peer
* @param {Observable} [connectionIds] An observable sequence of peerids that will be used to initiate dataConnections
* @returns {Observable} An observable sequence of DataConnections
*/
function fromPeer(peer, connectionIds) {
var fromEvent = Rx.Observable.fromEvent;
var throwError = Rx.Observable.throwError;
var open = fromEvent(peer, 'open');
var remoteConnections = fromEvent(peer, 'connection');
return Rx.Observable.when(
open.thenDo(function(){
var localConnections = connectionIds.map((id) => {return peer.connect(id);});
return remoteConnections.merge(localConnections);
})
).mergeAll();
}
function test0(){
var peer1 = new Peer("peer1", config.peer)
var peer2 = new Peer("peer2", config.peer)
var peer1connections = fromPeer(peer1, Rx.Observable.just("peer2"));
var peer2connections = fromPeer(peer2, Rx.Observable.empty());
peer1connections.subscribe(
(conn) => {console.log("Got a connection: " + conn.peer);},
(err) => {console.log("Error: " + err);},
() => {console.log("complete");}
);
peer2connections.subscribe(
(conn) => {console.log("Got a connection: " + conn.peer);},
(err) => {console.log("Error: " + err);},
() => {console.log("complete");}
);
peer1.on('open', ()=>{console.log("open1")})
peer2.on('open', ()=>{console.log("open2")})
peer2.on('connection', ()=>{console.log("connect2")})
};
// => Got a connection: peer2
// => open1
// => connect2
// => open2
// => Got a connection: peer1 -- This will not always be printed to the console.
jsfiddle
with this code to play with it? – user3743222