How to use rxjs - 10 common examples

To help you get started, we’ve selected a few rxjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github trufflesuite / drizzle-utils / packages / contract-state-stream / __tests__ / node_env.js View on Github external
web3,
      pollingInterval: 200,
    });

    const returnVal$ = createContractState$({
      newBlock$,
      artifact,
      provider,
    });

    // tap observable to make sure it emitted a "0" and then a "5"
    returnVal$
      .pipe(
        take(2),
        toArray(),
        tap(vals => {
          const twoValues = vals.map(x =>
            x.variables.storedData.value.toString(),
          );
          expect(twoValues).toEqual(["0", "5"]);
          expect(vals[0]).toMatchSnapshot(stateMatcher);
          expect(vals[1]).toMatchSnapshot(stateMatcher);
        }),
        finalize(() => {
          expect.assertions(3);
          done();
        }),
      )
      .subscribe();

    await contractInstance.methods.set(0).send({ from: accounts[0] });
    await contractInstance.methods.set(5).send({ from: accounts[0] });
github cloudfoundry / stratos / src / frontend / app / shared / components / cf-role-checkbox / cf-role-checkbox.component.ts View on Github external
ngOnInit() {
    this.isOrgRole = !this.spaceGuid;
    const users$ = this.store.select(selectUsersRolesPicked);
    // Org? Org manager. Space? Org manager or space manager
    const canEditRole$ = this.isOrgRole ?
      this.userPerms.can(CurrentUserPermissions.ORGANIZATION_CHANGE_ROLES, this.cfGuid, this.orgGuid) :
      canUpdateOrgSpaceRoles(
        this.userPerms,
        this.cfGuid,
        this.orgGuid,
        this.spaceGuid);

    this.sub = this.cfRolesService.existingRoles$.pipe(
      combineLatest(this.cfRolesService.newRoles$, users$, canEditRole$),
      filter(([existingRoles, newRoles, users, canEditRole]) => !!users.length && !!newRoles.orgGuid)
    ).subscribe(([existingRoles, newRoles, users, canEditRole]) => {
      this.orgGuid = newRoles.orgGuid;
      if (this.role) {
        console.log(existingRoles, newRoles);
        // TODO: RC existingRoles needs to have newly assigned roles... this list comes from users in a pagination section...
      }
      const { checked, tooltip } = CfRoleCheckboxComponent.getCheckedState(
        this.role, users, existingRoles, newRoles, this.orgGuid, this.spaceGuid);
      this.checked = checked;
      this.tooltip = tooltip;
      this.disabled = !canEditRole ||
        CfRoleCheckboxComponent.isDisabled(this.isOrgRole, this.role, users, existingRoles, newRoles, this.orgGuid, checked);
    });
  }
github wardbell / rxjs-in-ng / src / app / app.component.ts View on Github external
templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  hasArt = false;
  numberOfBackgrounds = 16;
  movingBg$ = new Subject().pipe(startWith(true));

  backgroundArr = randommizeArrayOrder(
    Array.from(
      { length: this.numberOfBackgrounds },
      (e, i) => `Url(/assets/mainbg${i + 1}.jpg`
    )
  );

  key$ = fromEvent(this.document, 'keyup').pipe(
    filter((ev: KeyboardEvent) => ['F2', 'F4'].includes(ev.key)),
    tap(ev => ev.preventDefault()), // side effect take away original meaning of key   map((ev: KeyboardEvent) => ev.key),
    map(ev => ev.key),
    tap(k => console.log('key', k))
  );

  @ViewChild('main') main;

  constructor(
    public raki: RakiService,
    private swUrlService: SwUrlService,
    @Inject(DOCUMENT) private document: any
  ) {}

  ngOnInit() {
    if (this.hasArt) {
github alexjlockwood / ShapeShifter / src / app / pages / editor / components / canvas / canvasoverlay.directive.ts View on Github external
ngAfterViewInit() {
    if (this.actionSource === ActionSource.Animated) {
      // Animated canvas specific setup.
      this.registerSubscription(
        combineLatest(
          // TODO: don't think this is necessary anymore? only need to query playback service now?
          merge(
            this.playbackService.asObservable().pipe(map(event => event.vl)),
            this.store.select(getVectorLayer),
          ),
          this.store.select(getCanvasOverlayState),
        ).subscribe(
          ([
            vectorLayer,
            { hiddenLayerIds, selectedLayerIds, isActionMode, selectedBlockLayerIds },
          ]) => {
            this.vectorLayer = vectorLayer;
            this.hiddenLayerIds = hiddenLayerIds;
            this.selectedLayerIds = selectedLayerIds;
            this.isActionMode = isActionMode;
            this.selectedBlockLayerIds = selectedBlockLayerIds;
            this.draw();
          },
        ),
github T-Systems-MMS / phonebook / Phonebook.Frontend / src / app / services / api / current-user.service.ts View on Github external
public getCurrentUserId(): Observable {
    return this.getCurrentUserObject().pipe(
      map(str => {
        // Userstring Layout is "Domain\\user"
        // This returns just the "user"
        return str.user.toLowerCase().split('\\')[1];
      })
    );
  }
github Ninja-Squad / globe42 / frontend / src / app / person-files / person-files.component.spec.ts View on Github external
it('should upload a file', () => {
    // create component with 1 file
    const personFileService = TestBed.get(PersonFileService);
    spyOn(personFileService, 'list').and.returnValues(of([files[0]]), of(files));

    const fakeEvents = new Subject();
    spyOn(personFileService, 'create').and.returnValues(fakeEvents);

    const fixture = TestBed.createComponent(PersonFilesComponent);
    fixture.detectChanges();

    // trigger change
    const fileChangeEvent = {
      target: {
        files: [{
          name: files[1].name
        }]
      }
    } as any;
github w11k / ngx-componentdestroyed / src / tslint / BadComponent.ts View on Github external
import {Component, OnDestroy, OnInit} from "@angular/core";
import {of} from "rxjs";
import {map, takeUntil} from "rxjs/operators";
import {untilComponentDestroyed} from "../index";

class SomeClass {
    subscribe() {
    }
}

@Component({})
class BadComponent implements OnInit, OnDestroy {

    observable = of(1);
    stop = of(1);

    ngOnInit() {
        // Error
        this.observable.pipe(
            map(i => i),
            takeUntil(this.stop),
            map(i => i),
        ).subscribe();

        // Error
        this.observable.pipe(
            map(i => i),
            untilComponentDestroyed(this),
            map(i => i),
        ).subscribe();
github lordfriend / Deneb-UI / src / timeline-meter / timeline-meter.ts View on Github external
ngAfterViewInit(): void {
        let meterEl = this.meter.nativeElement;
        let container = this.container.nativeElement;
        let renderWrapper = this.renderWrapper.nativeElement;
        // for mouse event
        this._subscription.add(
            observableFromEvent(meterEl, 'mousedown').pipe(
                filter(() => {
                    return this.timestampList && this.timestampList.length > 0;
                }),
                mergeMap((event: MouseEvent) => {
                    event.preventDefault();
                    return observableFromEvent(document, 'mousemove').pipe(
                        takeUntil(observableFromEvent(document, 'mouseup')));
                }),
                map((event: MouseEvent) => {
                    return Math.max(0, Math.min(event.clientY - renderWrapper.getBoundingClientRect().top, this.availableHeight));
                }),)
                .subscribe((pos: number) => {
                    this.scrollTo(pos);
                })
        );

        // for click
github cloudfoundry / stratos / src / frontend / packages / core / src / features / cloud-foundry / user-invites / user-invite.service.ts View on Github external
constructor(
    private store: Store,
    private http: HttpClient,
    private snackBar: MatSnackBar,
    cfEndpointService: CloudFoundryEndpointService,
    private currentUserPermissionsService: CurrentUserPermissionsService,
    private activeRouteCfOrgSpace: ActiveRouteCfOrgSpace,
    private confirmDialog: ConfirmationDialogService,
  ) {
    this.configured$ = cfEndpointService.endpoint$.pipe(
      filter(v => !!v && !!v.entity),
      // Note - metadata could be falsy if smtp server not configured/other metadata properties are missing
      map(v => v.entity.metadata && v.entity.metadata.userInviteAllowed === 'true')
    );

    this.canConfigure$ = combineLatest(
      waitForCFPermissions(this.store, this.activeRouteCfOrgSpace.cfGuid),
      this.store.select('auth')
    ).pipe(
      map(([cf, auth]) =>
        cf.global.isAdmin &&
        auth.sessionData['plugin-config'] && auth.sessionData['plugin-config'].userInvitationsEnabled === 'true')
    );
  }
github fabric8-ui / fabric8-ui / src / app / services / area.service.ts View on Github external
getAreas(): Observable {
    // get the current iteration url from the space service
    if (this._currentSpace) {
      let areasUrl = this._currentSpace.relationships.areas.links.related;
      if (this.checkValidUrl(areasUrl)) {
        return this.http
          .get<{data: AreaModel[]}>(areasUrl)
          .pipe(
            map(response => {
              return response.data as AreaModel[];
            }),
            map((data) => {
              this.areas = data;
              return this.areas;
            }),
            catchError((error: Error | any) => {
              if (error.status === 401) {
                //this.auth.logout(true);
              } else {
                console.log('Fetch area API returned some error - ', error.message);
                return Promise.reject([] as AreaModel[]);
              }
            })
          );
      } else {
        this.logger.log('URL not matched');
        return ObservableOf([] as AreaModel[]);
      }
    } else {
      return throwError('nospace');
    }
  }