waitForTxnDetailDataToLoad(): Observable<any> {

    this.txnDetail$ = Observable.combineLatest(
           this.store.select(fromRoot.getCustomerDetails),
           this.store.select(fromRoot.getLoggedInUser),
           this.store.select(fromRoot.getDetailTransaction),
           this.store.select(fromRoot.getSelectedpropertyName),
           (custDtls, loggedInUser, txnDtl, propertyName) => {
             var businessInfo = {firstName:loggedInUser.firstName,
                                 lastName:loggedInUser.lastName,
                                 email:loggedInUser.email,
                                 phoneNumber: (undefined != loggedInUser.phoneNum)?loggedInUser.phoneNum:'Not Provided',
                                 faxNumber:(undefined != loggedInUser.faxNum)?loggedInUser.faxNum:'Not Provided',
                                 addr: custDtls.contactAddress,
                                 fedTaxId:(undefined != custDtls.fedTaxId)?custDtls.fedTaxId:'Not Provided',
                                 languagePref:custDtls.correspondenceLang
                               }
             return {businessInfo,txnDtl,propertyName}
         });

     return new Observable(observer => {
           this.txnDetail$.subscribe(dtl => {
              if(dtl.txnDtl.isLoadingSuccess){
                observer.next(dtl);
                observer.complete();
              }
          })
     });
  }
 constructor(public store: Store<any[]>) {
   this.filteredTodos = Observable.combineLatest(store.select('todos'), store.select('visibility'), (todos: any, visibilityFilter: any) => todos.filter(visibilityFilter.filter));
   this.todos = store.select('todos');
   this.visibilityFilter = store.select('visibility');
   this.completedCount = this.todos.map((todos: any) => todos.reduce((count, todo) => todo.completed ? count + 1 : count, 0));
   this.activeCount = this.todos.map((todos: any) => todos.length - (todos.reduce((count, todo) => todo.completed ? count + 1 : count, 0)));
 }
Example #3
0
  return new Promise<void>(resolve => {
    let timer;

    if (typeof timeout === 'number' && timeout > 0) {
      timer = setTimeout(() => {
        console.warn(chalk.yellow(`Timed out while waiting for NgZone to become stable after ${timeout}ms! This is a serious performance problem!`));
        console.warn(chalk.yellow('This likely means that your application is stuck in an endless loop of change detection or some other pattern of misbehaviour'));
        console.warn(chalk.yellow('In a normal application, a zone becomes stable very quickly'));
        console.warn('Proceeding with render operation even though the zone is not stable: this is a very dangerous thing to do!')
        console.warn('You can adjust the zone-becomes-stable timeout with ApplicationBuilder::stabilizeTimeout(), or zero to disable');
        resolve();
      },
      timeout);
    }

    const combined = Observable.combineLatest(applicationRef.isStable, requests.requestsPending(),
      (appStable, pending) => {
        return appStable && pending === 0;
      });

    const subscription = combined.subscribe(v => {
      if (v === true) {
        if (subscription) {
          subscription.unsubscribe();
        }
        if (timer != null) {
          clearTimeout(timer);
        }
        resolve();
      }
    });
  });
 constructorZone3.run(() => {
   combinedObservable =
       Rx.Observable.combineLatest(observable1, observable2, (x: number, y: number) => {
         expect(Zone.current.name).toEqual(constructorZone3.name);
         return x + y;
       });
 });
Example #5
0
    //TODO: create as a computed store service: 
    //  http://onehungrymind.com/handle-multiple-angular-2-models-ngrx-computed-observables/
    constructor(private _store: Store<AppState> /*, private _itemService: TripService*/) {
        this.searchTab = new Tab();
        this.searchTab.id = 'tab-id-search';
        this.searchTab.title = 'Search';
        this.searchTab.template = 'search';
        this.searchTab.active = true;
        this.searchTab.closeable = false;
        this.searchTab.itemId = '';

        this.activeTabId$ = _store.select(x => x.trip.activeTabId);
        this.openItems$ = _store.select(x => x.trip.openList);
        this.tabs$ = this.openItems$
            .combineLatest(this.activeTabId$)
            .map(([trips, activeId]) => {
                this.searchTab.active = activeId === this.searchTab.id || !activeId;
                return [this.searchTab].concat(trips.map(item => {
                    let exists = item.Trip && item.Trip.TripId && item.Trip.TripId.length > 0;
                    let t = new Tab();
                    t.id = item.PlaceholderId;
                    t.title = exists ? item.Trip.DepartDate : 'Add Trip'; //TODO: what is a good title here??
                    t.template = 'item';
                    t.active = activeId === t.id;
                    t.closeable = true;
                    t.item = item;
                    t.itemId = item.Trip.TripId;
                    return t;
                }));
            });
    }
export function todoItemDataFlow(intent: TodoItemIntent, todoProperty$: Observable<Todo>){
    const editing$ = Observable.merge<boolean, boolean>(
        intent.startEdit$.map(() => true),
        intent.stopEdit$.map(() => false),
        intent.cancelEdit$.map(() => false)
    ).startWith(false);

    const viewModel$ = todoProperty$
        .combineLatest(editing$, (todoProperty, editing) => Object.assign({}, todoProperty, { editing }));

    const delete$ = intent.delete$
        .withLatestFrom(todoProperty$, (_, todo: Todo) => todo)
        .map(x => ({ id: x.id }));

    const edit$ = intent.stopEdit$
        .withLatestFrom(todoProperty$, (title: string, todo: Todo) => ({ title, todo }))
        .filter(x => x.title !== x.todo.title)
        .map(x => ({ id: x.todo.id, title: x.title }));

    const toggle$ = intent.toggleTodo$
        .withLatestFrom(todoProperty$, (_, todo: Todo) => todo)
        .map(todo => ({ id: todo.id }));

    return {
        viewModel$,
        delete$,
        edit$,
        toggle$
    };
}
Example #7
0
export const compileTickObservable = (items$, stop$, start$) => {

  /**
   * Observable stream that emits the number of ms passed since it's started at interval of minInterval
   */
  const timer$ = Observable.interval(minInterval)
    .map(val => val * minInterval);

  /**
   * This observable combines both the timer stream and the stream injected from the store (which contains the items)
   * Outputs the items whose interval match the time
   */
  const matchedItems$ = Observable.combineLatest(
    items$,
    timer$,
    (items, timer) => ({items: items, timer: timer}) // mapping for combineLatest as last param
  )
    .takeUntil(stop$) // stop the stream when receiving incoming from the stop$ stream (a click)
    .filter(data => {
      return matchItemsIntervalToTimer(data.items, data.timer).length; // filter the timers without any matches
    })
    .distinct((previousData, nextData) => previousData.timer === nextData.timer) // make sure we dont emit twice the same timer
    .map(data => ({items: matchItemsIntervalToTimer(data.items, data.timer), timer: data.timer })); // only return the matches for this time

  // we return a stream that will start when start$ receives incomming
  return start$
    .startWith({}) // start automatically the stream when incomming data at init
    .switchMapTo(matchedItems$); // simply pass the logic above
};
        it("should not cause the command to be executed twice when the condition changes during execution", (done) => {
            class MyInnerClass extends ReactiveObject {
                constructor() {
                    super();
                    this.prop = "";
                }

                public get prop(): string {
                    return this.get("prop");
                }
                public set prop(val: string) {
                    this.set("prop", val);
                }
            }
            class MyClass extends ReactiveObject {
                constructor() {
                    super();
                    this.value = new MyInnerClass();
                }
                public get value(): MyInnerClass {
                    var val = this.get("value");
                    if (!val) {
                        val = new MyInnerClass();
                        this.value = val;
                    }
                    return val;
                }
                public set value(val: MyInnerClass) {
                    this.set("value", val);
                }
            }
            var obj: MyClass = new MyClass();
            var innerCommand = ReactiveCommand.create((a) => {
                return obj.value.prop;
            });
            var isValid = obj.whenAnyValue(vm => vm.value.prop).map(c => {
                return !!c.trim();
            });
            var canExecute = Observable.combineLatest(
                isValid,
                innerCommand.isExecuting.map(ie => !ie),
                (valid, notRunning) => {
                    return valid && notRunning
                }
            )
            var count: number = 0;
            var command: ReactiveCommand<any, any> = ReactiveCommand.createFromObservable((a) => {
                count++;
                obj.value = new MyInnerClass();
                return innerCommand.execute();
            }, canExecute);
            obj.value.prop = "Custom";
            command.execute().subscribe(() => {
                expect(count).to.equal(1);
            }, err => done(err), () => done());
        });
 onSubmit(value: any): void {
   var self : ThreadDetailComponent = this;
   var id : string;
   Observable.combineLatest<string,string>(
                   this._routeParams.switchMap((params: Params) => (id = params['id'])),
                   this.rService.observeServicesLink('threads')
             ).flatMap<Response>(([id,link], index) => this.rService.post('posts', {thread:link+'/'+id, body:value['message']})
             ).flatMap(response=>this.rService.observeService('threads', '/'+id+'/posts')
           ).take(1).subscribe(response=>{self.data['posts']=response.json()._embedded['posts'];self.postForm.reset();}
                             ,error=>console.log(error));
 }
Example #10
0
    constructor(private store: Store<fromRoot.State>, private formsService: FormsService, private appConfig: AppConfigService) {

        this.initSubs = Observable.combineLatest(
            store.select(fromRoot.getRelationshipIdForStartStopTxn),
            store.select(fromRoot.getSelectedPropertyBPType)
        ).subscribe((result: any) => {
            this.relationshipId = result[0];
            this.bpType = result[1];
        })

        this.downloadRestUrl = this.appConfig.readEnvironment('downloadRestUrl');
    }
Example #11
0
  ngOnInit() {
    this.combinedSub = Observable.combineLatest(this.af.auth, this.route.params)
      .filter((args) => args[0] != null)
      .subscribe((args) => {
        let auth = args[0];
        let routeParams = args[1];

        this.contentId = routeParams["id"];
        this.userId = auth.uid;
        this.commentsRef = this.af.database.list(`/entry/byContentId/${this.contentId}/`);
      });
  }
  constructor(private store: Store<AppStore>) {
    this.context = Observable.combineLatest(
        store.select('sessions'),
        store.select('selectedUser'),
        (sessions: Session[], selectedUser: User) => {
          return {
            sessions: sessions.filter(session => selectedUser.sessions.indexOf(session.id) > -1)
          };
        });

    this.context
      .subscribe(c => console.log('ContextService.context', c));
  }
Example #13
0
  constructor(private store: Store<AppStore>) {
    this.gadget = Rx.Observable.combineLatest(
      store.select('items'),
      store.select('widgets'),
      (items: Item[] = [], widgets: Widget[] = []) => {
        return {
          items: [...items],
          widgets: [...widgets]
        }
      });

    this.gadget
      .subscribe(c => console.log('GadgetService.gadget', c));
  }
Example #14
0
  ionViewDidEnter() {
    if (this.hasMap) {
      this._resizeSubscription = Observable.combineLatest(
        this.section$,
        this.isMapFullscreen$
      ).subscribe(([section, isFullscreen]) => {
        this.content.resize();

        // Hack to make it happen after resize is done
        setTimeout(() => {
          this.calculateOffset(section, isFullscreen);
        }, 0);
      });
    }
  }
Example #15
0
export const onContinue$Fac = (game: iGame): Observable<iGame> => {
  const stars$ = stars$Fac(game.actors.stars);
  const heroShip$ = heroShip$Fac(game.actors.heroShip);
  const heroShots$ = heroShots$Fac(game.actors.heroShots, heroShip$);
  const enemyShips$ = enemyShips$Fac(game.actors.enemyShips);
  return Observable.combineLatest(
    stars$,
    heroShip$,
    heroShots$,
    enemyShips$,
    (stars, heroShip, heroShots, enemyShips) => {
      // check collide between heroShip and enemyShips
      enemyShips.forEach((enemyShip, index, enemyShips) => {
        const enemyShipLeftTip = {x: enemyShip.x - config.enemyShip.halfBottomLength, y: enemyShip.y - config.enemyShip.halfBottomLength}
        const enemyShipRightTip = {x: enemyShip.x + config.enemyShip.halfBottomLength, y: enemyShip.y - config.enemyShip.halfBottomLength}
        if (
          isCollided(heroShip, enemyShip) || isCollided(heroShip, enemyShipLeftTip) || isCollided(heroShip, enemyShipRightTip) 
        ) {
          game.gameOver = true;
        }
      })
      // check collide between heroShots and enemyShips
      heroShots.forEach((heroShot, index, heroShots) => {
        enemyShips.forEach((enemyShip, jindex, enemyShips) => {
          if (isCollided(heroShot, enemyShip)) {
            enemyShips.splice(jindex, 1);
            heroShots.splice(index, 1);
          }
        })
      })
      return {
        actors: {
          stars,
          heroShip,
          heroShots,
          enemyShips
        },
        paused: game.paused,
        firstRun: game.firstRun,
        gameOver: game.gameOver
      }
    }
  )


}
Example #16
0
  ngOnInit() {
    this.isInputFocused = false;
    this.id = this.route.snapshot.params['id'];
    this.tasksObservable = this.taskListService.getTaskList(this.id);
    this.listName = this.taskListService.getListName(this.id);
    this.editableSubscription =
        Observable
            .combineLatest(
                this.authenticationService.observableUserId,
                this.taskListService.getListOwner(this.id))
            .subscribe((ids) => { this.isEditable = ids[0] === ids[1]['$value']; });

    this.tasksSubscription = this.tasksObservable.subscribe((tasks) => {
      this.tasks = tasks;
      this.sortTasksByName();
      this.setDistances();
    });
  }
 constructorZone3.run(() => {
   combinedObservable = Rx.Observable.combineLatest(observable1, observable2);
 });
    constructor(todoStore: TodoStorage) {
        super([
            "areAllTodosComplete",
            "todos",
            "editedTodo",
            "newTodo",
            "status",
            "_visibleTodos",
            "remainingText"
        ]);
        this._store = todoStore;
        this.editedTodo = null;
        this.newTodo = new Todo();
        this.todos = new ReactiveArray<Todo>();
        this.areAllTodosComplete = false;
        this.completedTodos = this.todos.derived.whenAnyItemProperty().filter(t => t.completed).build();
        this.incompleteTodos = this.todos.derived.whenAnyItemProperty().filter(t => !t.completed).build();
        this.save = ReactiveCommand.createFromTask((a) => {
            return this._store.putTodos(this.todos.toArray());
        });

        var isNotSaving = this.save.isExecuting.map(executing => !executing);

        this.loadTodos = ReactiveCommand.createFromTask((a) => {
            return this._store.getTodos();
        });
        this.loadTodos.results.subscribe(todos => {
            this.todos.splice(0, this.todos.length, ...todos);
        });

        this.deleteTodo = ReactiveCommand.createFromObservable((a: Todo) => {
            var todoIndex = this.todos.indexOf(a);
            if (todoIndex >= 0) {
                this.todos.splice(todoIndex, 1);
                return this.save.execute();
            } else {
                return Observable.of(false);
            }
        });

        this.toggleTodo = ReactiveCommand.createFromObservable((todo: Todo) => {
            todo.completed = !todo.completed;
            return this.save.execute();
        }, isNotSaving);

        var hasValidNewTodo = this.whenAnyValue(vm => vm.newTodo.title)
            .map(title => this.isValidTitle(title));

        var canAddTodo = Observable.combineLatest(
            hasValidNewTodo,
            isNotSaving,
            (validTodo, isNotSaving) => validTodo && isNotSaving);

        this.addTodo = ReactiveCommand.createFromObservable((a) => {
            this.newTodo.title = this.newTodo.title.trim();
            this.todos.unshift(this.newTodo.copy());
            this.resetNewTodo();
            return this.save.execute();
        }, canAddTodo);

        this.editTodo = ReactiveCommand.create((todo: Todo) => {
            this._originalTodo = todo.copy();
            this.editedTodo = todo;
            return {};
        });

        this.finishEditing = ReactiveCommand.createFromObservable(a => {
            if (this.editedTodo) {
                this.editedTodo.title = this.editedTodo.title.trim();
                if (this.editedTodo.title.length == 0) {
                    return this.deleteTodo.execute(this.editedTodo);
                }
                this.editedTodo = null;
            }
            return this.save.execute().do(saved => {
                if (saved) {
                    this._originalTodo = null;
                    this.editedTodo = null;
                }
            });
        }, isNotSaving);

        var canUndo = this.whenAnyValue(vm => vm.editedTodo, vm => vm.todos, (e, todos) => e !== null && todos !== null);

        this.undo = ReactiveCommand.create(a => {
            if (this.editedTodo && this._originalTodo) {
                this.editedTodo.title = this._originalTodo.title;
                this.editedTodo.completed = this._originalTodo.completed;
            }
            this.editedTodo = null;
            this._originalTodo = null;
            return true;
        }, canUndo);

        var areAllComplete = this.todos.computed.every(t => t.completed);
        var hasTodos = this.todos.whenAnyValue(t => t.length).map(length => length > 0);
        var canMarkAllComplete = Observable.combineLatest(hasTodos, areAllComplete, isNotSaving, (hasTodos, complete, notSaving) => hasTodos && !complete && notSaving);
        var canMarkAllIncomplete = Observable.combineLatest(hasTodos, areAllComplete, isNotSaving, (hasTodos, complete, notSaving) => hasTodos && complete && notSaving);
        Observable.zip(hasTodos, areAllComplete, (hasTodos, complete) => hasTodos && complete)
            .subscribe(complete => {
                this.areAllTodosComplete = complete;
            });

        this.markAllComplete = ReactiveCommand.createFromObservable(a => {
            var completedTodos = this.todos;
            completedTodos.forEach(t => {
                t.completed = true;
            });
            return this.save.execute();
        }, canMarkAllComplete);

        this.markAllIncomplete = ReactiveCommand.createFromObservable(a => {
            var incompleteTodos = this.todos;
            incompleteTodos.forEach(t => {
                t.completed = false;
            });
            return this.save.execute();
        }, canMarkAllIncomplete);

        this.toggleAllComplete = ReactiveCommand.createFromObservable(a => {
            var allComplete = this.todos.every(t => t.completed);
            if (allComplete) {
                return this.markAllIncomplete.execute();
            } else {
                return this.markAllComplete.execute();
            }
        }, isNotSaving);

        this.clearComplete = ReactiveCommand.createFromObservable(a => {
            var todos = this.todos;
            for (var i = todos.length - 1; i >= 0; i--) {
                var t = todos.getItem(i);
                if (t.completed) {
                    todos.splice(i, 1);
                }
            }
            return this.save.execute();
        }, isNotSaving);

        this.whenAnyValue(vm => vm.todos, vm => vm.status, (todos, status) => ({ todos, status }))
            .filter(args => args.todos !== null)
            .map(args => {
                if (args.status === "all") {
                    return args.todos;
                } else if (args.status === "complete") {
                    return args.todos.derived.whenAnyItemProperty().filter(t => t.completed).build();
                } else {
                    return args.todos.derived.whenAnyItemProperty().filter(t => !t.completed).build();
                }
            }).subscribe(todos => {
                this._visibleTodos = todos;
            });
        this.whenAnyValue(vm => vm._visibleTodos)
            .map(arr => arr.toObservable())
            .switch()
            .subscribe(arr => {
                this.set("visibleTodos", arr);
            });
        this.incompleteTodos.whenAnyValue(incomplete => incomplete.length)
            .map(l => l === 1 ? 'item left' : 'items left')
            .subscribe(text => this.remainingText = text);
        this.status = "all";
    }