Example #1
0
export function initObservable() {

    const click$ = Observable.fromEvent(document,'click');

    const mouse$ = Observable.fromEvent(document,'mousemove')
        .filter((move:MouseEvent) => move.clientY >=200);


    const combined$ = Observable.combineLatest(mouse$, click$);

    combined$.subscribe(
        combined => console.log(combined[0])
    );
}
 constructor(
     private store: Store<any>
 ){
     this.viewModel$ = Observable.combineLatest(
         store.select('todos'),
         store.select('visibilityFilter'),
         ({past = [], present = [], future = []}, visibilityFilter : string) => {
             return {
                 todos: this.visibleTodos(present, visibilityFilter),
                 totalTodos: present.length,
                 completedTodos: present.filter((todo : Todo) => todo.completed).length
             }
         }
     );
 }
 constructor(
     private store: Store<any>
 ){
     this.viewModel$ = Observable.combineLatest(
         store.select('todos'),
         store.select('visibilityFilter'),
         (todos : Array<Todo>, visibilityFilter : string) => {
             return {
                 todos: this.visibleTodos(todos, visibilityFilter),
                 totalTodos: todos.length,
                 completedTodos: todos.filter((todo : Todo) => todo.completed).length
             }
         }
     );
 }
export function typeahead(element: ElementRef, minLength = 1, debounceTime = 250): Observable<string> {
    return Observable.combineLatest(
        Observable.merge(
            Observable.fromEvent(element.nativeElement, 'compositionstart').map(() => true),
            Observable.fromEvent(element.nativeElement, 'compositionend').map(() => false),
        ).startWith(false),
        Observable.fromEvent(element.nativeElement, 'keyup'),
    )
    .filter(array => !array[0])
    .map(array => array[1])
    .map((event: KeyboardEvent) => (event.target as HTMLInputElement).value)
    .debounceTime(debounceTime)
    .distinctUntilChanged()
    .filter(value => value.length >= minLength);
}
 constructor(
   private store: Store<any>
   ) {
   this.viewModel$ = Observable.combineLatest(
     store.select('games'),
     store.select('visibilityFilter'),
     (games: Array<IGame>, visibilityFilter: string) => {
       return {
         games: this.visibleGames(games, visibilityFilter),
         totalGames: games.length,
         completedGames: games.filter((game: Game) => game.completed).length
       }
     }
     );
 }
  ngOnInit() {

    Observable.combineLatest([
      this.route.paramMap,
      this.route.queryParamMap
    ])
    .switchMap(combined => {
      let id = combined[0].get('id');
      let page = combined[1].get('page');

      return this.service.getAll();
    })
    .subscribe(followers => this.followers = followers);
  
      
    }
Example #7
0
/**
 * compute ratio
 */
export default function(options: ResponsiveOptions) {

  const scaleSubject = new BehaviorSubject<any>(true);
  const scaleFn = compose(centeringOf(options.target), scalingOf(options.target));

  const hRatio = scaleSubject.map(horizontalRatioOf(options.width));
  const vRatio = scaleSubject.map(verticalRatioOf(options.height));

  const currentRatio = Observable.combineLatest(hRatio, vRatio).map((hv) => Math.min(hv[0], hv[1]));
  currentRatio.subscribe(scaleFn);

  return {
    scale        : scaleSubject,
    currentRatio : currentRatio
  };
}
      .subscribe(data => {

        // map source format to time series data
        let mapped = data.map(single => {
          let typed:TimeSeriesData = {
            value : single[1],
            date : new Date(single[0])
          }
          return typed;
        });

        // store data
        this.data = mapped;


        // DEBUG - we could map the data to percentual changes to the last quarter and offer this as another option...
        // let change = this.data.map(d => d.value).map((value, index, array) => index == 0 ? 0 : value / array[index-1] - 1);
        // console.warn(change);


        // store all years for which we have data
        this.years = this.data
          .map(tsd => tsd.date.getUTCFullYear())
          .filter((elem, pos, arr) => arr.indexOf(elem) == pos);

        // ensure that from <= to in all cases
        this.yearFrom.valueChanges.subscribe(newFrom => {
          if (this.yearTo.value < newFrom)
            this.yearTo.updateValue(newFrom);
        });
        this.yearTo.valueChanges.subscribe(newTo => {
          if (this.yearFrom.value > newTo)
            this.yearFrom.updateValue(newTo);
        });
        
        // whenever one of the years (from,to) change, update the filtered data
        Observable.combineLatest(this.yearFrom.valueChanges, this.yearTo.valueChanges)
          .debounceTime(50)
          .subscribe(yearRange => {
            let from:number = yearRange[0];
            let to:number = yearRange[1];
            this.filteredData = this.data.filter(dataPoint => dataPoint.date.getUTCFullYear() >= from && dataPoint.date.getUTCFullYear() <= to);
          });

        // set initial values to first and last available year
        this.showAllData();
      });
Example #9
0
    getCantonOptions(): Observable<IMultiSelectOption[]> {
        const mapToOption = (key: string) => ({
            id: key,
            name: `global.reference.canton.${key}`
        });

        const translateOption = (option: IMultiSelectOption) => {
            return this.translateService.stream(option.name)
                .map((translation) => Object.assign({}, option, { name: translation }));
        };
        const translatedOptions = Object.keys(Canton)
            .filter((key) => !isNaN(Number(Canton[key])))
            .map(mapToOption)
            .map(translateOption);

        return Observable.combineLatest(translatedOptions);
    }
Example #10
0
    it('should work', () => {
      const subjectA = new Subject<string>();
      const subjectB = new Subject<string>();
      const log: string[] = [];
      const subject = Observable.combineLatest(subjectA, subjectB).subscribe(([a, b]) => {
        log.push(`${a}-${b}`);
      });

      subjectA.next('hello');
      expect(log).toEqual([]);

      subjectB.next('world');
      expect(log).toEqual(['hello-world']);

      subjectA.next('bye');
      expect(log).toEqual(['hello-world', 'bye-world']);
    });
Example #11
0
    it('should use visibilityFilter to filter todos', () => {

      const filterVisibleTodos = (visibilityFilter, todos) => {
        let predicate;
        if (visibilityFilter === VisibilityFilters.SHOW_ALL) {
          predicate = () => true;
        }
        else if (visibilityFilter === VisibilityFilters.SHOW_ACTIVE) {
          predicate = (todo) => !todo.completed;
        }
        else {
          predicate = (todo) => todo.completed;
        }
        return todos.filter(predicate);
      };

      let currentlyVisibleTodos;

      Observable.combineLatest(store.select('visibilityFilter'), store.select('todos'), filterVisibleTodos)
        .subscribe(visibleTodos => {
          currentlyVisibleTodos = visibleTodos;
        });

      expect(currentlyVisibleTodos.length).toBe(2);

      store.dispatch({ type: SET_VISIBILITY_FILTER, payload: VisibilityFilters.SHOW_ACTIVE });

      expect(currentlyVisibleTodos.length).toBe(1);
      expect(currentlyVisibleTodos[0].completed).toBe(false);

      store.dispatch({ type: SET_VISIBILITY_FILTER, payload: VisibilityFilters.SHOW_COMPLETED });

      expect(currentlyVisibleTodos.length).toBe(1);
      expect(currentlyVisibleTodos[0].completed).toBe(true);

      store.dispatch({ type: COMPLETE_ALL_TODOS });

      expect(currentlyVisibleTodos.length).toBe(2);
      expect(currentlyVisibleTodos[0].completed).toBe(true);
      expect(currentlyVisibleTodos[1].completed).toBe(true);

      store.dispatch({ type: SET_VISIBILITY_FILTER, payload: VisibilityFilters.SHOW_ACTIVE });

      expect(currentlyVisibleTodos.length).toBe(0);

    });
Example #12
0
 ngOnInit() {
   Observable.combineLatest(
     this.appService.getStatistics(),
     this.userService.getStatistics(),
     this.nodeClient.getStatistics(),
     this.podClient.getStatistics()
   ).subscribe(
     response => {
       this.appTotal = response[0].data.total;
       this.userTotal = response[1].data.total;
       this.nodeTotal = response[2].data.total;
       this.podTotal = response[3].data.total;
     },
     error => {
       this.messageHandlerService.handleError(error);
     }
   );
 }
    public ngOnInit(): void {
        let input$: Observable<string> = Observable.fromEvent(this.el.nativeElement.querySelector("input"), "keyup")
            .map((e: any) => e.target.value)
            .startWith("");
        this.matchingWines$ = Observable.combineLatest(input$, this.wines$)
            .map((resp: [string, Array<Wine>]) => {
                let searchVal: string = resp[0];
                let wines: Array<Wine> = resp[1];
                return _.filter(wines, (wine: Wine) => {
                    return wine.name.toLowerCase().indexOf(searchVal.toLowerCase()) > -1;
                });
            });

        this.numberOfWines$ = this.wines$.map((wines: Array<Wine>) => {
            return _.sumBy(wines, (wine: Wine) => {
                return wine.inStock;
            });
        });
    }
Example #14
0
 constructor(
     private store: Store<any>
 ){
     const viewModel$ = Observable.combineLatest(
         store.select('todos'),
         store.select('visibilityFilter'),
         (todos : Array<Todo>, visibilityFilter : string) => {
             return {
                 todos: this.visibleTodos(todos, visibilityFilter),
                 totalTodos: todos.length,
                 completedTodos: todos.filter((todo : Todo) => todo.completed).length
             }
         }
     ).share();
     //expose to view
     this.todos$ = viewModel$.map(vm => vm.todos);
     this.totalTodos$ = viewModel$.map(vm => vm.totalTodos);
     this.completedTodos$ = viewModel$.map(vm => vm.completedTodos);
 }
  ngOnInit() {
    this.querySub = this.router
      .routerState
      .queryParams
      .subscribe(params => {
        const term = params['term'];
        if (term) {
          this.actions.setTerm(decodeURIComponent(term));
        }
        const page = +params['page'] || 0;
        this.actions.setPage(page);
      });

    // Do search & update query params if either search params change
    this.stateSub = this.term$.combineLatest(this.page$).subscribe(n => {
      this.actions.search();
      this.updateQueryParams();
    });
  }
Example #16
0
  fetchEvents(): Observable<IEvent[]> {
    this._http.get(BASE_URL)
        .map(res => res.json())
        .map(payload => ({type: 'ADD_EVENTS', payload}))
        .subscribe(action => this.store.dispatch(action));

    return this.events$ = Observable.combineLatest(
               this.store.select('events'), this.store.select('developers'),
               (events: any[], developers: any[]) => {
                 return events.map(event => {
                   var speakers: Array<IDeveloper> =
                       Object.keys(event.speakers)
                           .map(
                               speakerId =>
                                   developers.find(developer => developer.id === speakerId) ||
                                   ({id: speakerId}));
                   return Object.assign({}, event, {speakers: speakers});
                 });
               });
  }
  waitForSavingUserLoad(): Observable<any> {

      this.userInfo$ = Observable.combineLatest(
              this.store.select(fromRoot.getSavedUserInfo),
              this.store.select(fromRoot.getAdminCustomerList),
              this.store.select(fromRoot.getLoggedInUserSecurityRole),
              this.store.select(fromRoot.getSaveUserConfirmation),
              (user,customerList,securityRole,confirmation) => {
                    return {user,customerList,securityRole,confirmation}
            });

       return new Observable(observer => {
             this.userInfo$.subscribe(data => {
                if(data.confirmation.isLoadingSuccess){
                  observer.next(data);
                  observer.complete();
                }
            })
       });
  }
  constructor() {
    this.visibilityFilterDispatcher = new BehaviorSubject('SHOW_ALL');
    this.todoDispatcher = new BehaviorSubject([]);
    this.currentTodos = [];

    this.state = Observable.combineLatest(
      this.visibilityFilterDispatcher,
      this.todoDispatcher,
      (visibilityFilter, todos) => {
        return {
          visibilityFilter,
          todos,
        };
      }
    );

    this.state.subscribe((currState: IState) => {
      console.log('State Change'); console.log(currState);
      this.currentTodos = currState.todos;
    });
  }
  public removePoolCoinsOrAlgos(
    bookmark: UserProfile['bookmarks']['pools'][''],
  ): Observable<void> {
    return this.userId
      .combineLatest(this.userBookmarks)
      .first()
      .switchMap(
        ([uid, bookmarks]) => {
          const index = Object.keys(bookmarks.pools)
            .find(key => bookmarks.pools[key] === bookmark);

          if (index == null) {
            throw new Error('Can\'t find bookmark to remove');
          }

          const path = validPath(['v2', 'user', uid, 'bookmarks', 'pools', index]);
          return Observable.fromPromise(
            this.db.removeObject(path),
          );
        },
    );
  }
  waitForStopConfirmationLoad(): Observable<any> {

      this.stopConfirmation$ = Observable.combineLatest(
              this.store.select(fromRoot.getCustomerDetails),
              this.store.select(fromRoot.getLoggedInUser),
              this.store.select(fromRoot.getSelectedUnits),
              this.store.select(fromRoot.getSelectedSrvcAddrDetails),
              this.store.select(fromRoot.getSelectedpropertyName),
              this.store.select(fromRoot.getStartServiceConfirmation),
            (custDtls, loggedInUser,selectedUnits,selectedSrvcAddress,selectedpropName,confirmation) => {
                return{
                    businessInfo:{firstName:loggedInUser.firstName,
                                  lastName:loggedInUser.lastName,
                                  email:loggedInUser.email,
                                  phoneNumber: loggedInUser.phoneNum,
                                  extn: loggedInUser.phoneNumExtn,
                                  faxNumber:loggedInUser.faxNum,
                                  addr: custDtls.contactAddress,
                                  fedTaxId:(undefined != custDtls.fedTaxId)?custDtls.fedTaxId:'Not Provided',
                                  languagePref:custDtls.correspondenceLang
                                },
                    selectedUnits: selectedUnits.unitList,
                    serviceAddress: selectedSrvcAddress,
                    selectedpropName:selectedpropName,
                    confirmation:confirmation.confirmation,
                    isLoadingSuccess: confirmation.isLoadingSuccess
                }
            });

       return new Observable(observer => {
             this.stopConfirmation$.subscribe(data => {
                if(data.isLoadingSuccess){
                  observer.next(data);
                  observer.complete();
                }
             })
       });
  }
	getAllWithFilter(store: Store<AppState>): Observable<Hero[]> {
		return Observable.combineLatest(
			store.select(this.getAll()),
			store.select(this.getFilter()),
			(heroes, filter) => {
				if (!filter) {
					return heroes;
				}
				const fuse = new Fuse(heroes, {
					keys: [
						{
							name: "title",
							weight: 0.8,
						}, {
							name: "caption",
							weight: 0.2
						}
					]
				});
				return fuse.search<Hero>(filter);
			}
		);
	}
  ngOnInit() {
    this.recordSearchService.cursor$
      .takeUntil(this.isDestroyed)
      .subscribe(cursor => {
        this.recordCursor = cursor;
        this.changeDetectorRef.markForCheck();
      });

    const searchSub = Observable.combineLatest(
      this.route.params,
      this.route.queryParams,
      (params, queryParams) => {
        return { params, queryParams };
      }).do((route: RouteType) => {
        this.recordType = route.params.type;
      }).filter((route: RouteType) => Boolean(route.queryParams.query))
      .switchMap((route: RouteType) => this.recordSearchService.search(route.params.type, route.queryParams.query))
      .takeUntil(this.isDestroyed)
      .subscribe(recordIds => {
        this.foundRecordIds = recordIds;
        this.changeDetectorRef.markForCheck();
      });
  }
  ngOnInit(): void {
    this.appId = parseInt(this.route.parent.snapshot.params['id']);
    let namespaceId = this.cacheService.namespaceId;
    let pvcId = parseInt(this.route.snapshot.params['pvcId']);

    Observable.combineLatest(
      this.pvcService.list(PageState.fromState({sort: {by: 'id', reverse: false}}, {pageSize: 1000}), 'false', this.appId + ''),
      this.appService.getById(this.appId, namespaceId),
    ).subscribe(
      response => {
        this.pvcs = response[0].data.list.sort((a, b) => a.order - b.order);
        this.initOrder(this.pvcs);
        this.app = response[1].data;
        pvcId = this.getPvcId(pvcId);
        if (pvcId) {
          this.pvcId = pvcId;
          if (this.router.url.indexOf('status') == -1) {
            this.navigateToList(this.app.id, pvcId);
          }

          this.publishService.listStatus(PublishType.PERSISTENT_VOLUME_CLAIM, this.pvcId).subscribe(
            response => {
              this.publishStatus = response.data;
            },
            error => {
              this.messageHandlerService.handleError(error);
            }
          );
        }
        // this.navigateToList(this.app.id, this.pvcId);
      },
      error => {
        this.messageHandlerService.handleError(error);
      }
    );
  }
 constructor(
   private articleService: ArticleService,
   private store: Store<AppState>
 ){
   const tag$=store.select('main','tag');
   this.currentPage$=store.select('main','currentPage');
   const subject=new Subject<Article[]>();
   const articleSource =Observable.combineLatest(tag$,this.currentPage$)
     .debounceTime(0)
     .map(([tag,page])=>this.articleService.getArticles(tag?tag.id:'',page))
     .mergeAll()
     .do(data=>this.store.dispatch(new FetchArticle(data)))
     .map(()=>store.select('main','articles'))
     .mergeAll();
   articleSource.subscribe(subject);
   this.articles$=subject;
   this.addPageAction$=this.currentPage$
     .map(page=>new ChangePage(page+1));
   this.reducePageAction$=this.currentPage$
     .map(page=>new ChangePage(page-1));
   this.maxPage$=subject
     .map(articles=>articles.length===10?this.currentPage$.map(page=>page+1):this.currentPage$)
     .mergeAll();
 }
  fetchCommunities(): Observable<ICommunity[]> {
    this._http.get(BASE_URL)
        .map(res => res.json())
        .map(payload => ({type: 'ADD_COMMUNITIES', payload}))
        .subscribe(action => this.store.dispatch(action));

    return this.communities$ = Observable.combineLatest(
               this.store.select('communities'), this.store.select('developers'),
               (communities: any[], developers: any[]) => {
                 return communities.map(community => {
                   var members: Array<IDeveloper> =
                       Object.keys(community.members)
                           .map(
                               memberId =>
                                   developers.find(developer => developer.id === memberId) ||
                                   ({id: memberId}));
                   var contact: IDeveloper =
                       developers.find(developer => developer.id === community.contact) ||
                       ({id: community.contact});
                   var trying = Object.assign({}, community, {members: members, contact: contact});
                   return trying;
                 });
               });
  }
Example #26
0
  combine(...statesName) {
    let states = statesName.map((stateName) => this.select(stateName));

    return Observable.combineLatest(...states);
  }
Example #27
0
    it('should use visibilityFilter to filter todos', () => {
      store.dispatch({ type: ADD_TODO, payload: { text: 'first todo' } });
      store.dispatch({ type: ADD_TODO, payload: { text: 'second todo' } });
      store.dispatch({
        type: COMPLETE_TODO,
        payload: { id: state.value.todos[0].id },
      });

      const filterVisibleTodos = (visibilityFilter: any, todos: any) => {
        let predicate;
        if (visibilityFilter === VisibilityFilters.SHOW_ALL) {
          predicate = () => true;
        } else if (visibilityFilter === VisibilityFilters.SHOW_ACTIVE) {
          predicate = (todo: any) => !todo.completed;
        } else {
          predicate = (todo: any) => todo.completed;
        }
        return todos.filter(predicate);
      };

      let currentlyVisibleTodos: Todo[] = [];

      Observable.combineLatest(
        store.select('visibilityFilter'),
        store.select('todos'),
        filterVisibleTodos
      ).subscribe(visibleTodos => {
        currentlyVisibleTodos = visibleTodos;
      });

      expect(currentlyVisibleTodos.length).toBe(2);

      store.dispatch({
        type: SET_VISIBILITY_FILTER,
        payload: VisibilityFilters.SHOW_ACTIVE,
      });

      expect(currentlyVisibleTodos.length).toBe(1);
      expect(currentlyVisibleTodos[0].completed).toBe(false);

      store.dispatch({
        type: SET_VISIBILITY_FILTER,
        payload: VisibilityFilters.SHOW_COMPLETED,
      });

      expect(currentlyVisibleTodos.length).toBe(1);
      expect(currentlyVisibleTodos[0].completed).toBe(true);

      store.dispatch({ type: COMPLETE_ALL_TODOS });

      expect(currentlyVisibleTodos.length).toBe(2);
      expect(currentlyVisibleTodos[0].completed).toBe(true);
      expect(currentlyVisibleTodos[1].completed).toBe(true);

      store.dispatch({
        type: SET_VISIBILITY_FILTER,
        payload: VisibilityFilters.SHOW_ACTIVE,
      });

      expect(currentlyVisibleTodos.length).toBe(0);
    });
Example #28
0
 .flatMap((res) => {
   return Observable.combineLatest(res);
 });
Example #29
0
  .switchMap(
    (needsUpdate) =>
      needsUpdate
        ? Observable.fromPromise(updateServiceWorker().then(() => true))
        : Observable.of(false)
  )
  .shareReplay();

/**
 * Whether there is new content available if you reload DIM.
 *
 * We only need to update when there's new content and we've already updated the service worker.
 */
export const dimNeedsUpdate$ = Observable.combineLatest(
  serverVersionChanged$,
  serviceWorkerUpdated$,
  contentChanged$,
  (serverVersionChanged, updated, changed) => serverVersionChanged || (updated && changed)
).distinctUntilChanged();

/**
 * If Service Workers are supported, install our Service Worker and listen for updates.
 */
export default function registerServiceWorker() {
  if (!('serviceWorker' in navigator)) {
    return;
  }
  navigator.serviceWorker
    .register('/service-worker.js')
    .then((registration) => {
      // If we have access to the broadcast channel API, use that to listen
      // for whether there are actual content updates from Workbox.
 .switchMap((criteria: FilterCriteria) =>
   Observable.combineLatest(
     this._playerService.getPlayer(this.playerIdParam),
     this._statsService.getPlayerStats(this.playerIdParam, criteria)
   )).subscribe(