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$
    };
}
 // 全てのStoreのStateUpdateをComponentに通知する。
 // Componentはこのストリームを受けてcd.markForCheck()すればOnPush環境でViewを動的に更新できる。  
 get storeNotificator$$() {
   // return this.mainStore.takeLatest$(_NOTIFICATION_); 
   const observables = this.stores.map(store => store.takeLatest$<any>(_NOTIFICATION_));
   return Observable
     .merge(...observables);
   // .debounceTime(10); // あまり細かくストリームを流す必要もないのでdebounceTime
 }
Example #3
0
  /**
   *
   * @param eventId string
   * Get event informations
   */
  getEvent(eventId): Observable<any> {
    const cacheKey: string = 'event_' + eventId;

    let cacheStream = this.cache.getCache(cacheKey);

    let webStream = this.storage.getValue('id').switchMap(id => {
      return this.http.get(this.baseUrl + '/chillers/' + id + '/events/' + eventId)
        .map(res => res.json())
        .filter(res => res)
        .map(res => {
          if (res.chillerid == id) {
            res.mine = true;
          } else {
            res.mine = false;
          }

          return res;
        })
        .map(res => {
          this.cache.setCache(cacheKey, res);

          return res;
        });
    });

    return Observable.merge(cacheStream, webStream)
      .filter(res => res);
  }
Example #4
0
    select<T extends Component, T2 extends Component>(v1: Type<T>, v2: Type<T2>): Rx.Observable<[T,T2]> {
    let r1 = Rx.Observable.of(...this.state.getComponentMap(v1).values());
    let r2 = Rx.Observable.of(...this.state.getComponentMap(v2).values());

    return Rx.Observable
      .merge<T,T2>(r1, r2)
      .groupBy(c => c.entityId)
      .flatMap(group => group.reduce((acc, curr) => [...acc, curr], []))
      .filter(a => a.length === 2);
  }
Example #5
0
 .flatMap(i => {
     let j1 = Observable.create(s => {
         $.get("http://localhost:8080/double?number=" + (i), d => s.next(d));
     });
     let j2 = Observable.create(s => {
         $.get("http://localhost:8080/double?number=" + (i + 100), d => s.next(d));
     });
     let j3 = Observable.create(s => {
         $.get("http://localhost:8080/double?number=" + (i + 1000000), d => s.next(d));
     });
     return Observable.merge(j1, j2, j3);
 })
Example #6
0
  selects<T extends Component, T2 extends Component>(v1: Type<T>, v2: Type<T2>): Rx.Observable<[T,T2]> {
    let r1 = fromDictionary(this.state.getComponentMap(v1));
    let r2 = fromDictionary(this.state.getComponentMap(v2));

    return Rx.Observable
      .merge<T,T2>(r1, r2)
      .groupBy(c => c.entityId)
      .flatMap(group => group.reduce((acc, curr) => [...acc, curr], []))
      .filter(arr => arr.length === 2)
      .map(arr => {
        return [arr[0], arr[1]]
      })
  }
 .subscribe(limitCheckResult => {
   if (limitCheckResult) {
     const request = serviceClient
       .createRequestResponseOperation(
         'executeTrade',
         executeTradeRequest
       )
       .publish()
       .refCount()
     disposables.add(
       Observable.merge(
         request
           .map(dto => {
             const trade = tradeMapper.mapFromTradeDto(dto.Trade)
             log.info(
               `execute response received for: ${executeTradeRequest}. Status: ${trade.status}`,
               dto
             )
             return createExecuteTradeResponse(trade)
           })
           // if we never receive a response, mark request as complete
           .timeout(
             EXECUTION_REQUEST_TIMEOUT_MS,
             Scheduler.asap.schedule(() =>
               createExecuteTradeResponseForError(
                 'Trade execution timeout exceeded',
                 executeTradeRequest
               )
             )
           ),
         // show timeout error if request is taking longer than expected
         Observable.timer(EXECUTION_CLIENT_TIMEOUT_MS)
           .map(() =>
             createExecuteTradeResponseForError(
               'Trade execution timeout exceeded',
               executeTradeRequest
             )
           )
           .takeUntil(request)
       ).subscribe(o)
     )
   } else {
     o.next(
       createExecuteTradeResponseForError(
         'Credit limit exceeded',
         executeTradeRequest
       )
     )
   }
 })
Example #8
0
  /**
   *
   * Return the profile id: number
   */
  getProfileId(): Observable<any> {
    let id = this.storage.getValue('id')
      .filter(id => id)
      .switchMap(id => {
        return this.http.get(this.baseUrl + '/chillers/' + id)
          .map(res => res.json())
          .filter(res => res)
          .map(res => {
            return id;
          });
      }
      );

    return Observable.merge(id)
      .filter(res => res);
  }
 jQuery.getJSON(url, ()=> {
     var path = `https://${source}/Snapshots/business${businessId}/station${stationId}/${fileName}.jpg`;
     jQuery(this.elRef.nativeElement).find('.newImage').fadeOut(200);
     var img = this.renderer.createElement(this.elRef.nativeElement, 'img', null);
     jQuery(img).addClass('snap');
     var int$ = Observable.interval(500).do(()=> {
         img.src = path;
     })
     var $err = Observable.fromEvent(img, 'error').do(()=>{
         jQuery(this.elRef.nativeElement).find('.snap').remove();
     })
     var load$ = Observable.fromEvent(img, 'load')
     var subscription = Observable.merge(int$, $err).takeUntil(load$).delay(500).subscribe((res)=> {
         subscription.unsubscribe();
     })
 });
Example #10
0
  /**
   *
   * @param id string
   * Get chill information when editing
   */
  getChill(id): Observable<any> {
    const cacheKey: string = 'chill_' + id;

    let cacheStream = this.cache.getCache(cacheKey);

    let webStream = this.http.get(this.baseUrl + '/chills/' + id)
      .map(res => res.json())
      .filter(res => res)
      .map(res => {
        this.cache.setCache(cacheKey, res);

        return res;
      });

    return Observable.merge(cacheStream, webStream)
      .filter(res => res);
  }
    ngOnInit() {
        let whispers: Observable<ChatType> = this.socketService_.whisper$
            .map<ChatType>(chat => {
                let message = "[" + chat.direction + ": " + chat.username + "]: " + chat.message;
                return { username: chat.username, message, direction: chat.direction, type: "whisper" };
            });

        let shouts: Observable<ChatType> = this.socketService_.chat$
            .map<ChatType>(chat => {
                let message = chat.username + ": " + chat.message;
                return { username: chat.username, message, direction: chat.direction, type: "chat" };
            });

        this.chats = shouts.merge(whispers)
            .map<ChatType[]>((chat: ChatType) => Array(chat))
            .scan<ChatType[]>((i, j) => i.concat(j));
    };
Example #12
0
  cycle({ CounterView }:{ CounterView: ViewSource }) {
    const action$ = Observable.merge<number, number>(
      CounterView.actions('increment').map(ev => 1),
      CounterView.actions('decrement').map(ev => -1)
    )

    const count$ = action$
      .startWith(0)
      .scan<number>((total, change) => total + change)

    const sinks = {
      CounterView: count$.map((count) => ({ 
        count: count
      }))
    }
    
    return sinks
  }
Example #13
0
  /**
   *
   * @param evtId string
   * Get saved expenses of this event
   */
  getExps(evtId): Observable<any> {
    const cacheKey: string = 'expenses_' + evtId;

    let cacheStream = this.cache.getCache(cacheKey);

    let webStream = this.storage.getValue('id').switchMap(id => {
      return this.http.get(this.baseUrl + '/chillers/' + id + '/events/' + evtId + '/expenses')
        .map(res => res.json())
        .filter(res => res)
        .map(res => {
          this.cache.setCache(cacheKey, res);

          return res;
        });
    });

    return Observable.merge(cacheStream, webStream)
      .filter(res => res);
  }
Example #14
0
  getSentInvitation(): Observable<any> {
    const cacheKey: string = 'sent_invitations';

    let cacheStream = this.cache.getCache(cacheKey);

    let webStream = this.storage.getValue('id').switchMap(id => {
      return this.http.get(this.baseUrl + '/chillers/' + id + '/friends/invitation_sent')
        .map(res => res.json())
        .filter(res => res)
        .map(res => {
          this.cache.setCache(cacheKey, res);

          return res;
        });
    });

    return Observable.merge(cacheStream, webStream)
      .filter(res => res);
  }
Example #15
0
  /**
   *
   * @param customChillId string
   * Get details of a custom chill
   */
  getCustomChill(customChillId): Observable<any> {
    const cacheKey: string = 'my_custom';

    let cacheStream = this.cache.getCache(cacheKey);

    let webStream = this.storage.getValue('id').switchMap(id => {
      return this.http.get(this.baseUrl + '/chillers/' + id + '/custom_chills/' + customChillId)
        .map(res => res.json())
        .filter(res => res)
        .map(res => {
          this.cache.setCache(cacheKey, res);

          return res;
        });
    });

    return Observable.merge(cacheStream, webStream)
      .filter(res => res);
  }
Example #16
0
 constructor(req: Request, browserXHR: CustomBrowserXhr, baseResponseOptions?: ResponseOptions) {
   // When subscribed to, creates a new XMLHttpRequest object with an upload progress event listener
   // Makes sure this XHR is reused in the following call to super(), which will then send the XHR.
   let progressResponse = new Observable<Response>( (responseObserver: Observer<Response>) => {
     // console.log('extending xhr with progress');
     let xhr = browserXHR.build();
     browserXHR.useCachedForNextBuild();
     
     let onProgress = (event) => {
       // console.log('xhr progress', event);
       let response = new Response(new ResponseOptions());
       response['isProgressEvent'] = true; // Add unique field to test for this sort of event
       // response.status = 102; // 102 Processing (1xx Informational)
       response.bytesLoaded = event.loaded;
       response.totalBytes = event.total;
       // Add all fields from XHR ProgressEvent 
       response['lengthComputable'] = event.lengthComputable;
       response['loaded'] = event.loaded;
       response['total'] = event.total;
       responseObserver.next(response);
     };
     let onLoad = (event) => {
       // console.log('xhr complete', event);
       responseObserver.complete();
     };
     (xhr.upload || xhr).addEventListener('progress', onProgress);
     xhr.addEventListener('load', onLoad);
     return () => {
       // console.log('xhr abort', event);
       (xhr.upload || xhr).removeEventListener('progress', onProgress);
       xhr.removeEventListener('load', onLoad);
     }
   });
   
   // Populates this.response with an Observable<Response>
   // When subscribed to, it will call browserXHR.build to obtain an XMLHttpRequest object and send it
   super(req, browserXHR, baseResponseOptions);
   
   // Merge progress responses into the default response stream
   // Make sure progress responses are subscribed to first
   this.response = progressResponse.merge(this.response);
 }
  private _bindListeners() {
    console.log('should listen for incoming events');
    // this.prob = Observable.fromEvent(this.io, 'probe:single');
    // this.bid = Observable.fromEvent(
    //   this._io, 'auction:new:bid'
    // ).share();

    let probeSource = Observable.fromEvent(
      this._io, 'bid:probe'
    )
    let bidSource = Observable.fromEvent(
      this._io, 'auction:new:bid'
    )

    this.bid = Observable.merge(probeSource, bidSource);

    this.bidder = Observable.fromEvent(
      this._io, 'bidder:joined:auction'
    ).share();
  }
function todosReducers(intent: TodosIntent): Observable<(todosStore: TodosStore) => TodosStore> {
    const addTodoReducer$ = intent.addTodo$
        .map(({ title }) => title.trim())
        .filter(title => !!title)
        .map(title => (todosStore: TodosStore) => ({
            todos: [
                ...todosStore.todos,
                { id: cuid(), title, completed: false }
            ]
        }));

    const deleteTodoReducer$ = intent.deleteTodo$
        .map(({ id }) => (todosStore: TodosStore) => ({
            todos: todosStore.todos.filter(todo => todo.id !== id)
        }));

    const editTodoReducer$ = intent.editTodo$
        .map(({ id, title }) => (todosStore: TodosStore) => ({
            todos: todosStore.todos.map(todo => todo.id !== id ? todo : Object.assign({}, todo, { title }))
        }));

    const toggleTodoReducer$ = intent.toggleTodo$
        .map(({ id }) => (todosStore: TodosStore) => ({
            todos: todosStore.todos.map(todo => todo.id !== id ? todo : Object.assign({}, todo, { completed: !todo.completed }))
        }));

    const removeCompletedReducer$ = intent.removeCompleted$
        .map(() => (todosStore: TodosStore) => ({
            todos: todosStore.todos.filter(todo => !todo.completed)
        }));

    const toggleAllReducer$ = intent.toggleAll$
        .map(() => (todosStore: TodosStore) => {
            const allCompleted = todosStore.todos.reduce((x, y) => x && y.completed, true);
            return {
                todos: todosStore.todos.map(todo => Object.assign({}, todo, { completed: !allCompleted }))
            };
        });

    return Observable.merge(addTodoReducer$, deleteTodoReducer$, editTodoReducer$, toggleTodoReducer$, removeCompletedReducer$, toggleAllReducer$);
}
  constructor() {
    this.source_A = new Rx.Subject();
    this.source_B = new Rx.Subject();
    const src_A = Rx.Observable.from(this.source_A)
                    .map((value)=>{return value +'--' });
    const src_B = Rx.Observable.from(this.source_B);
    const merged_src = Rx.Observable.merge(src_A, src_B)
                        .map((value)=>{ return value + '||||'});

    merged_src.subscribe(
      (value)=>{
        console.log("subscribe", value);
      },
      (error)=>{
        console.log(error)
      },
      ()=>{
        console.log("completed")
      }
    )

  }
Example #20
0
  /**
   *
   * @param friendId string
   * Get friend event list
   */
  getEventsList(friendId) {
    const cacheKey: string = 'event_list_' + friendId;

    let cacheStream = this.cache.getCache(cacheKey);

    let webStream = this.storage.getValue('id').switchMap(id => {
      let params = new URLSearchParams();
      params.set('chiller', friendId);

      return this.http.get(this.baseUrl + '/chillers/' + id + '/events', { search: params })
        .map(res => res.json())
        .filter(res => res)
        .map(res => {
          this.cache.setCache(cacheKey, res);

          return res;
        });
    });

    return Observable.merge(cacheStream, webStream)
      .filter(res => res);
  }
Example #21
0
  /**
   * Get pending friends
   */
  getPendingFriends(): Observable<any> {
    const cacheKey: string = 'pending_friends';

    let cacheStream = this.cache.getCache(cacheKey);

    let webStream = this.storage.getValue('id').switchMap(id => {
      let params = new URLSearchParams();
      params.set('pending', 'yes');

      return this.http.get(this.baseUrl + '/chillers/' + id + '/friends', { search: params })
        .map(res => res.json())
        .filter(res => res)
        .map(res => {
          this.cache.setCache(cacheKey, res);

          return res;
        });
    });

    return Observable.merge(cacheStream, webStream)
      .filter(res => res);
  }
  cycle({ CounterSharedView }:{ CounterSharedView: ViewSource }) {
    const action$ = Observable.merge<number, number>(
      CounterSharedView.actions('increment').map(ev => 1),
      CounterSharedView.actions('decrement').map(ev => -1)
    )
    
    const count$ = action$
      .startWith(0)
      .scan<number>((total, change) => total + change)

    const sinks = {
      CounterSharedView: count$.map((count) => ({ 
        count,
      }))
    }
    console.log('running cycle', this)
    // const sinks = {
    //   // CounterSharedView: Observable.of({ count: 0 })
    // }
    
    return sinks
  }
Example #23
0
    PAPER: 1,
    SCISSORS: 2
}

const ROCK = rpsEnum.ROCK;
const PAPER = rpsEnum.PAPER;
const SCISSORS = rpsEnum.SCISSORS;

const opponentThrows$ = Observable.of(ROCK, /*Error('blah'),*/ PAPER, SCISSORS);
const interval$ = Observable.interval(1000);
const rock$ = Observable.fromEvent(rockButton, 'click').mapTo(ROCK);
const paper$ = Observable.fromEvent(paperButton, 'click').mapTo(PAPER);
const scissors$ = Observable.fromEvent(scissorsButton, 'click').mapTo(SCISSORS);
const reset$ = Observable.fromEvent(resetButton, 'click')
const playerThrow$ = Observable.merge(
    rock$, paper$, scissors$
);

const initialScore = {win: 0, lose: 0, tie: 0};

function calculateWins (score: any, throws: number[]) {
    let me = throws[0];
    let you = throws[1];

    if (me === you) {
        score.tie++;
    }
    if ((you + 1) % 3 === me) {
        score.win++;
    }
    if ((me + 1) % 3 === you) {
Example #24
0
 const observable3: any = constructorZone3.run(() => {
   return Rx.Observable.merge(observable1, observable2);
 });
import { Observable } from 'rxjs/Rx';

var first_stream : Observable<any>= Observable.interval(100).map(function(i : number){
    console.log('Stream A'+ i)
});
var second_stream  : Observable<any>=Observable.interval(200).map(function(i : number){
    console.log('Stream B' + i)
})
Observable.merge(first_stream, second_stream).subscribe(function(data){
    console.log(data)
}, function(err){
    console.log(err)
}, function(){
    console.log('completed')
})
//Returns an observable sequence that produces a value after each period.
//its another method of creating observables/data streams
 observable1 = constructorZone1.run(() => {
   return Rx.Observable.merge(
       Rx.Observable.interval(10).take(2), Rx.Observable.interval(15).take(1));
 });