为什么我错过了来自fromEvent的活动?

时间:2015-12-11 07:06:26

标签: javascript rxjs

我试图将Peer.JS Peer对象转换为可观察的dataConnections序列。但是,如下所示,即使始终建立连接,收到连接请求的对等体的可观察量也不会始终向其订户发出dataConnection。

根据我的阅读,fromEvent()会创建热门观察者?我的订阅者是否缺少dataConnection,因为它没有及早订阅?

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.

0 个答案:

没有答案