Beispiel #1
0
 public initialize() {
   return {
     view: {
       base: this.intent.test().pipe(
         scan((acc, next: any) => acc + 1, 1),
         share(),
         startWith(1),
       ),
       test: this.intent.test().pipe(
         scan((acc, next: any) => acc + 1, 1),
         share(),
         startWith(1),
       ),
       test2: this.subject.pipe(
         map(({ type, payload, states }) => {
           switch (type) {
             case 'subject-test':
               return payload + states.test2;
             default:
               return payload;
           }
         }),
         startWith(1),
       ),
     },
   };
 }
Beispiel #2
0
 constructor() {
   this.everySecond$ = timer(1000, 1000).pipe(
     share(),
   );
   this.everyHalfSecond$ = timer(500, 500).pipe(
     share(),
   );
 }
  share1() {
    // emit value in 1s
    const source = timer(1000);
    // log side effect, emit result
    const example = source.pipe(
      tap(() => console.log('***SIDE EFFECT***')),
      mapTo('***RESULT***')
    );

    /*
      ***NOT SHARED, SIDE EFFECT WILL BE EXECUTED TWICE***
      output:
      "***SIDE EFFECT***"
      "***RESULT***"
      "***SIDE EFFECT***"
      "***RESULT***"
    */
    const subscribe = example.subscribe(val => console.log(val));
    const subscribeTwo = example.subscribe(val => console.log(val));

    // share observable among subscribers
    const sharedExample = example.pipe(share());
    /*
      ***SHARED, SIDE EFFECT EXECUTED ONCE***
      output:
      "***SIDE EFFECT***"
      "***RESULT***"
      "***RESULT***"
    */
    const subscribeThree = sharedExample.subscribe(val => console.log(val));
    const subscribeFour = sharedExample.subscribe(val => console.log(val));
  }
 ngOnInit() {
   this.movieCollection = this.userService.getMovieCollection();
   this.movies$ = this.movieCollection.valueChanges().pipe(
     map(Movie.fromFirebaseCollection),
     share()
   );
 }
export function sampleObservable(obs: Observable<any>, scheduler?: any) {
  return obs.pipe(
    sampleTime(100, scheduler),
    share(),
    startWith('')
  );
}
 refresh() {
   this.params$ = this.sharedAboutService.getFeatureInfo()
     .pipe(map((featureInfo: FeatureInfo) => ({
       schedulesEnabled: featureInfo.schedulesEnabled
     })));
   this.counters$ = this.sharedAboutService.getFeatureInfo()
     .pipe(mergeMap(
       (featureInfo: FeatureInfo) => {
         const arr = [];
         arr.push(this.tasksService.getDefinitions({ q: '', size: 1, page: 0, sort: null, order: null }),
           this.tasksService.getExecutions({ q: '', size: 1, page: 0, sort: null, order: null }));
         if (featureInfo.schedulesEnabled) {
           arr.push(this.tasksService.getSchedules({ q: '', size: 1, page: 0, sort: null, order: null }));
         }
         return forkJoin([...arr])
           .pipe(map((counters) => {
             const result = {
               schedulesEnabled: featureInfo.schedulesEnabled,
               definitions: (counters[0] as Page<TaskDefinition>).totalElements,
               executions: (counters[1] as Page<TaskExecution>).totalElements
             };
             if (result.schedulesEnabled) {
               result['schedules'] = (counters[2] as Page<TaskSchedule>).totalElements;
             }
             return result;
           }));
       }
     ))
     .pipe(share());
 }
Beispiel #7
0
 return (input$: Observable<boolean>) => {
   let pending = null;
   const filteredInput$ = input$.pipe(
       map(open => ({open})), filter(event => {
         const currentlyOpen = isOpenedFn();
         if (currentlyOpen !== event.open && (!pending || pending.open === currentlyOpen)) {
           pending = event;
           return true;
         }
         if (pending && pending.open !== event.open) {
           pending = null;
         }
         return false;
       }),
       share());
   const delayedOpen$ = filteredInput$.pipe(filter(event => event.open), delayOrNoop(openDelay));
   const delayedClose$ = filteredInput$.pipe(filter(event => !event.open), delayOrNoop(closeDelay));
   return merge(delayedOpen$, delayedClose$)
       .pipe(
           filter(event => {
             if (event === pending) {
               pending = null;
               return event.open !== isOpenedFn();
             }
             return false;
           }),
           map(event => event.open));
 };
  it("should call unsubscribe on unsubscription if the Observable implementation has an unsubscribe function", () => {
  /* tslint:enable:max-line-length */

    let disposeHasBeenCalled = 0;
    const myObs = {
      subscribe(_a : () => void, _b : () => void, _c : () => {}) {
        return {
          unsubscribe() {
            disposeHasBeenCalled++;
          },
        };
      },
    };
    const rxObs = castToObservable(myObs);
    const sub1 = rxObs.subscribe();
    const sub2 = rxObs.subscribe();
    sub1.unsubscribe();
    sub2.unsubscribe();
    expect(disposeHasBeenCalled).toBe(2);

    // reset counter
    disposeHasBeenCalled = 0;

    const sharedRxObs = rxObs.pipe(share());
    const sharedSub1 = sharedRxObs.subscribe();
    const sharedSub2 = sharedRxObs.subscribe();
    sharedSub1.unsubscribe();
    sharedSub2.unsubscribe();
    expect(disposeHasBeenCalled).toBe(1);
  });
Beispiel #9
0
export function fromRef<T>(ref: DatabaseQuery, event: ListenEvent, listenType = 'on'): Observable<AngularFireAction<DatabaseSnapshot<T>>> {
  return new Observable<SnapshotPrevKey<T>>(subscriber => {
    const fn = ref[listenType](event, (snapshot, prevKey) => {
      subscriber.next({ snapshot, prevKey });
      if (listenType == 'once') { subscriber.complete(); }
    }, subscriber.error.bind(subscriber));
    if (listenType == 'on') {
      return { unsubscribe() { ref.off(event, fn)} };
    } else {
      return { unsubscribe() { } };
    }
  }).pipe(
    map(payload =>  {
      const { snapshot, prevKey } = payload;
      let key: string | null = null;
      if (snapshot.exists()) { key = snapshot.key; }
      return { type: event, payload: snapshot, prevKey, key };
    }),
    // Ensures subscribe on observable is async. This handles
    // a quirk in the SDK where on/once callbacks can happen
    // synchronously.
    delay(0),
    share()
  );
}
Beispiel #10
0
  public bindMessageHandlers(
    client: any,
    handlers: MessageMappingProperties[],
    transform: (data: any) => Observable<any>,
  ) {
    const disconnect$ = fromEvent(client, DISCONNECT_EVENT).pipe(
      share(),
      first(),
    );

    handlers.forEach(({ message, callback }) => {
      const source$ = fromEvent(client, message).pipe(
        mergeMap((payload: any) => {
          const { data, ack } = this.mapPayload(payload);
          return transform(callback(data)).pipe(
            filter(response => !isNil(response)),
            map(response => [response, ack]),
          );
        }),
        takeUntil(disconnect$),
      );
      source$.subscribe(([response, ack]) => {
        if (response.event) {
          return client.emit(response.event, response.data);
        }
        isFunction(ack) && ack(response);
      });
    });
  }