RxJS - Quick Tips #1

01/24/2021, Sun
Categories: #JavaScript
Tags: #RxJS

Conditional Activation of an Observable

Only make an observable run based on a ternary matching criteria.

// Third party modules
import { NEVER, of } from 'rxjs';

const evaluateToTrueCriteria = true;

// 'conditional$' will not run 'subscribe' when the ternary
// evaluates to the false branch
const conditional$ = evaluateToTrueCriteria ? of(true) : NEVER;
conditional$.subscribe((res) => console.log(res));

File System Wrapper

Use the "@rxnode/fs" module as a convenience wrapper around the default fs modules functions. The functions provided by "@rxnode/fs" will return an observable when called upon. Impose creation order with the help of RxJS's "concat".

// Third party modules
import { writeFile, mkdir } from '@rxnode/fs';
import { concat } from 'rxjs';
import { share, takeLast } from 'rxjs/operators';

// Paths for the folder and file
const newFolderPath = 'some/new/folder/path',
  newFileName = 'some/new/folder/path/withFile';

// The folder and file are turned into hot observables
// because the generation process should only be active once

// Folder creation
const createFolder$, = mkdir(newFolderPath)
  .pipe(share());

// File creation
const createFile$ = writeFile(newFileName, fileContent)
  .pipe(share());

// Wait for the folder to be generate before generating
// the file within it (when order matters)
concat(createFolder$, createFile$)

  // Prevent multiple triggers with only taking the
  // the last activation
  .pipe(takeLast(1))
  .subscribe(() => {
    console.log('Folder and file created');
  });

Wrap command line execution

Hook into a command line's execution to std out and completion with RxJs.

// Run the 'npm install' command using observables

// Native modules
import { spawn } from 'child_process';

// Third party modules
import { bindCallback } from 'rxjs';

const npmService = spawn('npm', ['install'], {
  cwd: "path/for/executing/npm/command"
});

const npmOnComplete$ = bindCallback(npmService.stdout.on),
  npmClose$ = npmOnComplete$.call(npmService, 'close');

// Listen to the completion event for the npm command
npmClose$
  .subscribe(() => {
    console.log('Finish npm install command');
  });