當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript Observable.fromEvent方法代碼示例

本文整理匯總了TypeScript中rx.Observable.fromEvent方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Observable.fromEvent方法的具體用法?TypeScript Observable.fromEvent怎麽用?TypeScript Observable.fromEvent使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rx.Observable的用法示例。


在下文中一共展示了Observable.fromEvent方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: RxConnection

      .flatMap<RxConnection>((conn: Connection): any => {
        // Disposable observable to close connection
        const connectionDisposer = Rx.Disposable.create(() => conn.close().catch(err => Rx.Observable.throw(err)));
        // New RxConnection stream
        const sourceConnection = Rx.Observable.of(new RxConnection(conn));
        // Stream of close events from connection
        const closeEvents = Rx.Observable.fromEvent(conn, 'close');
        // Stream of Errors from error connection event
        const errorEvents = Rx.Observable.fromEvent(conn, 'error')
          .flatMap((error: any) => Rx.Observable.throw(error));
        // Stream of open connections, that will emit RxConnection until a close event
        const connection = Rx.Observable
          .merge(sourceConnection, errorEvents)
          .takeUntil(closeEvents);

        // Return the disposable connection resource
        return Rx.Observable.using(
          () => connectionDisposer,
          () => connection
        )
      });
開發者ID:RobKamstra,項目名稱:rx-amqplib,代碼行數:21,代碼來源:RxAmqpLib.ts

示例2: initializeNonTouch

function initializeNonTouch(app) {
    var tapStream = Rx.Observable.fromEvent(document, "mousedown");
    var multiTapStream = tapStream
        .buffer((x) => tapStream.throttle(250))
        .map((list) => list.length)
        .filter((x) => x === 2)
        .subscribe(() => app.pause());

    var keyStream = Rx.Observable.fromEvent(document, "keydown")
        .do((e) => {
            switch (e.keyCode) {
                case 32: app.pause(); break;
                case 38: app.adjustSeconds(+1); break; // up
                case 40: app.adjustSeconds(-1); break; // down
                case 37: app.adjustMinutes(-1); break; // left
                case 39: app.adjustMinutes(+1); break; // right
            }
        })
        .subscribe();

    app.displayStatus("arrow keys & space!");
}
開發者ID:mieky,項目名稱:timepie,代碼行數:22,代碼來源:events.ts

示例3: getInput

function getInput(): Rx.Observable<string> {

    if (process.argv.length > 2) {
        var input: Node = fileinput.input();
        var observable = Rx1.Observable.fromEvent(input, 'line');
        var map = observable.map(line => line.toString().replace(fixNewLine, ""));
        return map;
    } else {
        return Rx1.Node.fromReadableStream(process.stdin)
            .selectMany(line => line.toString().split(fixNewLine))
            .windowWithCount(2, 1)
            .selectMany(l => l.reduce((acc, x) => {
                if (endsWith(acc, "}"))
                    return acc;
                else return acc + x;
            }, ""))
            .filter(item => (item[0] === "{"));
    }
}
開發者ID:isterin,項目名稱:generaterace,代碼行數:19,代碼來源:main.ts

示例4: getInput

function getInput():Rx.Observable<string>{
    if(process.argv.length > 2){
        return Rx.Observable.fromEvent(fileinput.input(),'line')
            .map(function (line) {return line.toString('utf8');})
            .map(function (line) {return line.replace(fixNewLine,"");});
    } else {
        return Rx.Node.fromReadableStream(process.stdin)
            .selectMany(function (line) {
                return line.toString().split(/(\r)?\n/)
            })
            .windowWithCount(2, 1)
            .selectMany(function (l) {
                return l.reduce(function (acc, x) {
                    if (endsWith(acc, "}") === true)
                        return acc;
                    else return acc + x;
                }, "");
            })
            .filter(function (item) {
                return item[0] === "{";
            });
    }
}
開發者ID:gwing33,項目名稱:generaterace,代碼行數:23,代碼來源:main.ts

示例5: constructor

    constructor(element: HTMLElement) {
        this._element = element;

        this._touchStart$ = rx.Observable.fromEvent<TouchEvent>(element, "touchstart");
        this._touchMove$ = rx.Observable.fromEvent<TouchEvent>(element, "touchmove");
        this._touchEnd$ = rx.Observable.fromEvent<TouchEvent>(element, "touchend");
        this._touchCancel$ = rx.Observable.fromEvent<TouchEvent>(element, "touchcancel");

        this._preventTouchMoveOperation$ = new rx.Subject<IPreventTouchMoveOperation>();
        this._preventTouchMove$ = new rx.Subject<boolean>();

        this._preventTouchMoveOperation$
            .scan<boolean>(
                (prevent: boolean, operation: IPreventTouchMoveOperation): boolean => {
                    return operation(prevent);
                },
                true)
            .subscribe();

        this._preventTouchMove$
            .map<IPreventTouchMoveOperation>(
                (prevent: boolean): IPreventTouchMoveOperation => {
                    return (previous: boolean): boolean => {
                        return prevent;
                    };
                })
            .subscribe(this._preventTouchMoveOperation$);

        this._touchMove$
            .map<IPreventTouchMoveOperation>(
                (te: TouchEvent): IPreventTouchMoveOperation => {
                    return (prevent: boolean): boolean => {
                        if (prevent) {
                            te.preventDefault();
                        }

                        return prevent;
                    };
                })
            .subscribe(this._preventTouchMoveOperation$);

        this._singleTouchMoveOperation$ = new rx.Subject<ITouchMoveOperation>();

        this._singleTouchMove$ = this._singleTouchMoveOperation$
            .scan<TouchMove>(
                (touch: TouchMove, operation: ITouchMoveOperation): TouchMove => {
                    return operation(touch);
                },
                new TouchMove());

        this._touchMove$
            .filter(
                (te: TouchEvent): boolean => {
                    return te.touches.length === 1 && te.targetTouches.length === 1;
                })
            .map<ITouchMoveOperation>(
                (te: TouchEvent): ITouchMoveOperation => {
                    return (previous: TouchMove): TouchMove => {
                        let touch: Touch = te.touches[0];

                        let current: TouchMove = new TouchMove(touch);

                        current.movementX = touch.pageX - previous.pageX;
                        current.movementY = touch.pageY - previous.pageY;

                        return current;
                    };
                })
            .subscribe(this._singleTouchMoveOperation$);

        let singleTouchStart$: rx.Observable<TouchEvent> = rx.Observable
            .merge(
                this._touchStart$,
                this._touchEnd$,
                this._touchCancel$)
            .filter(
                (te: TouchEvent): boolean => {
                    return te.touches.length === 1 && te.targetTouches.length === 1;
                });

        let multipleTouchStart$: rx.Observable<TouchEvent> = rx.Observable
            .merge(
                this._touchStart$,
                this._touchEnd$,
                this._touchCancel$)
            .filter(
                (te: TouchEvent): boolean => {
                    return te.touches.length >= 1;
                });

        let touchStop$: rx.Observable<TouchEvent> = rx.Observable
            .merge(
                this._touchEnd$,
                this._touchCancel$)
            .filter(
                (te: TouchEvent): boolean => {
                    return te.touches.length === 0;
                });

        this._singleTouch$ = singleTouchStart$
//.........這裏部分代碼省略.........
開發者ID:BogusCurry,項目名稱:mapillary-js,代碼行數:101,代碼來源:TouchService.ts

示例6: activate

export function activate(context: vscode.ExtensionContext) {

  // TODO use relative path
  childProcess = cp.spawn('/Users/jwin/VSCodeExtensions/vscode-haskell/haskell-src/ghc-engine/dist/build/hlsj/hlsj', [], {});
  if (childProcess.pid) {
    console.log('vscode-haskell: child-process started');
  }

  console.log('vscode-haskell: Extension activated');

  var activeEditor = vscode.window.activeTextEditor;
  const decorer = new decorator.Decorator(activeEditor);

  if (activeEditor) {
    // decorer.refreshDecorations(new vscode.Position(0, 0));
    // triggerUpdateDecorations(new vscode.Position(0, 0));
  }

  vscode.window.onDidChangeActiveTextEditor(editor => {
    console.log('onDidChangeActiveTextEditor');
    activeEditor = editor;
    decorer.activeEditor = activeEditor;
    if (editor) {
      // decorer.refreshDecorations(new vscode.Position(0, 0));
      // triggerUpdateDecorations(new vscode.Position(0, 0));
      
      // todo: move to disposal
      lexer.send('{{exit}}');
      // parser.send('{{exit}}');
    }
  }, null, context.subscriptions);

  vscode.workspace.onDidChangeTextDocument(event => {
    if (activeEditor && event.document === activeEditor.document) {
      var contentChanges: vscode.TextDocumentContentChangeEvent[] = event.contentChanges;
      // TODO also process multiple contentChanges (multi-cursor editing)
      eventEmitter.emit('data', contentChanges[0].range.start);
    }
  }, null, context.subscriptions);

  // TODO tsc error
  // src/extension.ts: error TS2339: Property 'fromEvent' does not exist on type 'ObservableStatic'.
  
  // wrap EventEmitter
  var source = Rx.Observable.fromEvent(eventEmitter, 'data').debounce(300 /* ms */); 

  // TODO extract subscriber for document
  subscription = source.subscribe(
    function(from: vscode.Position) {

      const start = process.hrtime();
      lexer.execute(activeEditor.document.getText()) // parser.execute(activeEditor.document.getText())
        .then((st) => {
          const end = process.hrtime(start);
          const dur = prettyHrtime(end);
          console.log("Promise resolved in " + dur + "\n" + st);
                                
          // todo: refactor to decorer, decorate correctly + optimally
          var result = JSON.parse(st);
          if (result.right != undefined) {
            // console.log("first pos: " + result.right[0][1]);
            testDecorations = [];
            R.forEach(element => {
              var from: vscode.Position = new vscode.Position(element[1][0], element[1][1]);
              var to: vscode.Position = new vscode.Position(element[1][2], element[1][3]);
              var range = new vscode.Range(from, to);
              testDecorations.push({ range: range, hoverMessage: null });
            }, result.right);
            activeEditor.setDecorations(testDecoration, testDecorations);
          }
        });
      // parser.execute(activeEditor.document.getText())
      //   .then((st) => {
      //     console.log("Promise resolved:\n" + st);
      //     // todo: decorate !
      //   });
    },
    function(err) {
      console.log('Error: ' + err);
    },
    function() {
      console.log('Completed');
    }
  );

  var testDecorations: vscode.DecorationOptions[] = [];

  var testDecoration: vscode.TextEditorDecorationType = vscode.window.createTextEditorDecorationType({
    cursor: 'crosshair',
    backgroundColor: 'rgba(255,0,0,0.3)'
  });

  // TODO remove obsolete debounce-fn
  // var timeout = null;
  // function triggerUpdateDecorations(from: vscode.Position) {
  //   console.log('triggerUpdateDecorations');
  //   decorer.refreshDecorations(from);
  //   if (timeout) {
  //     clearTimeout(timeout);
  //   }
//.........這裏部分代碼省略.........
開發者ID:duog,項目名稱:vscode-haskell,代碼行數:101,代碼來源:extension.ts

示例7:

        .map((e) => {
            e.preventDefault();

            return Rx.Observable.fromEvent(document, "touchmove")
                .takeUntil(Rx.Observable.fromEvent(document, "touchend"));
        })
開發者ID:mieky,項目名稱:timepie,代碼行數:6,代碼來源:events.ts

示例8: initializeTouch

function initializeTouch(app) {
    var tapStream = Rx.Observable.fromEvent(document, "touchstart");
    var multiTapStream = tapStream
        .buffer((x) => tapStream.throttle(250))
        .map((list) => list.length)
        .filter((x) => x === 2)
        .subscribe(() => app.pause());

    var THRESHOLD = 10;

    var touchStream = Rx.Observable.fromEvent(document, "touchstart")
        .do((e) => {
            this.dy = 0;
            this.dx = 0;
            this.startXy = {
                x: e.touches[0].pageX,
                y: e.touches[0].pageY
            };
        })
        .map((e) => {
            e.preventDefault();

            return Rx.Observable.fromEvent(document, "touchmove")
                .takeUntil(Rx.Observable.fromEvent(document, "touchend"));
        })
        .switch();

    var swipeVerticalStream = touchStream
        .filter(() => this.dy !== undefined)
        .do((e) => {
            if (Math.abs(e.touches[0].pageY - this.startXy.y) >= THRESHOLD) {
                delete this.dx;
            }
        })
        .map((e) => {
            var prevY = this.prevY || 0;
            var dir = e.touches[0].pageY > prevY ? -1 : 1;

            // Don't change values until locked on an axis, or if position unchanged
            if (this.dx !== undefined && this.dy !== undefined || e.touches[0].pageY === prevY) {
                dir = 0;
            }

            this.prevY = e.touches[0].pageY;
            return dir;
        })
        .throttleFirst(20) // slow down a bit
        .do((dir) => app.adjustSeconds(dir))
        .subscribe();

    var swipeHorizontalStream = touchStream
        .filter(() => this.dx !== undefined)
        .do((e) => {
            if (Math.abs(e.touches[0].pageX - this.startXy.x) >= THRESHOLD) {
                delete this.dy;
            }
        })
        .map((e) => {
            var prevX = this.prevX || 0;
            var dir = e.touches[0].pageX > prevX ? 1 : -1;

            // Don't change values until locked on an axis, or if position unchanged
            if (this.dx !== undefined && this.dy !== undefined || e.touches[0].pageX === prevX) {
                dir = 0;
            }

            this.prevX = e.touches[0].pageX;
            return dir;
        })
        .throttleFirst(40)
        .do((dir) => app.adjustMinutes(dir))
        .subscribe();

    app.displayStatus("swipe the time, double-tap to go!");
}
開發者ID:mieky,項目名稱:timepie,代碼行數:75,代碼來源:events.ts

示例9: constructor

    constructor(element: HTMLElement) {
        this._element = element;

        this._preventMouseDownOperation$ = new rx.Subject<IPreventMouseDownOperation>();
        this._preventMouseDown$ = new rx.Subject<boolean>();
        this._mouseMoveOperation$ = new rx.Subject<IMouseMoveOperation>();
        this._claimMouse$ = new rx.Subject<IMouseClaim>();

        this._mouseDown$ = rx.Observable.fromEvent<MouseEvent>(element, "mousedown");
        this._mouseLeave$ = rx.Observable.fromEvent<MouseEvent>(element, "mouseleave");
        this._mouseUp$ = rx.Observable.fromEvent<MouseEvent>(element, "mouseup");
        this._mouseOver$ = rx.Observable.fromEvent<MouseEvent>(element, "mouseover");

        this._mouseWheel$ = rx.Observable.fromEvent<WheelEvent>(element, "wheel");

        this._mouseWheel$
            .subscribe(
                (event: WheelEvent): void => {
                    event.preventDefault();
                });

        this._preventMouseDownOperation$
            .scan<boolean>(
                (prevent: boolean, operation: IPreventMouseDownOperation): boolean => {
                    return operation(prevent);
                },
                true)
            .subscribe();

        this._preventMouseDown$
            .map<IPreventMouseDownOperation>(
                (prevent: boolean): IPreventMouseDownOperation => {
                    return (previous: boolean): boolean => {
                        return prevent;
                    };
                })
            .subscribe(this._preventMouseDownOperation$);

        this._mouseDown$
            .map<IPreventMouseDownOperation>(
                (e: MouseEvent): IPreventMouseDownOperation => {
                    return (prevent: boolean): boolean => {
                        if (prevent) {
                            e.preventDefault();
                        }

                        return prevent;
                    };
                })
            .subscribe(this._preventMouseDownOperation$);

        this._mouseMove$ = this._mouseMoveOperation$
            .scan<MouseEvent>(
                (e: MouseEvent, operation: IMouseMoveOperation): MouseEvent => {
                    return operation(e);
                },
                new MouseEvent("mousemove"));

        rx.Observable
            .fromEvent<MouseEvent>(element, "mousemove")
            .map<IMouseMoveOperation>(
                (e: MouseEvent) => {
                    return (previous: MouseEvent): MouseEvent => {
                        if (e.movementX == null) {
                            e.movementX = e.offsetX - previous.offsetX;
                        }

                        if (e.movementY == null) {
                            e.movementY = e.offsetY - previous.offsetY;
                        }

                        return e;
                    };
                })
            .subscribe(this._mouseMoveOperation$);

        let dragStop$: rx.Observable<MouseEvent> = rx.Observable
            .merge<MouseEvent>([this._mouseLeave$, this._mouseUp$]);

        this._mouseDragStart$ = this._mouseDown$
            .selectMany<MouseEvent>((e: MouseEvent): rx.Observable<MouseEvent> => {
                return this._mouseMove$
                    .takeUntil(dragStop$)
                    .take(1);
            });

        this._mouseDrag$ = this._mouseDown$
            .selectMany<MouseEvent>((e: MouseEvent): rx.Observable<MouseEvent> => {
                return this._mouseMove$
                    .skip(1)
                    .takeUntil(dragStop$);
            });

        this._mouseDragEnd$ = this._mouseDragStart$
            .selectMany<MouseEvent>((e: MouseEvent): rx.Observable<MouseEvent> => {
                return dragStop$.first();
            });

        this._mouseOwner$ = this._claimMouse$
            .scan<{[key: string]: number}>(
//.........這裏部分代碼省略.........
開發者ID:BogusCurry,項目名稱:mapillary-js,代碼行數:101,代碼來源:MouseService.ts


注:本文中的rx.Observable.fromEvent方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。