LoginSignup
4
7

More than 3 years have passed since last update.

RxJS+TypeScriptのシンプルな構成の作成

Posted at

  • RxJS+TypeScriptの挙動を確認するための簡単な構成を作成する。

環境

  • 前提条件:nodeが入っていること。確認時のバージョンは以下
>node --version
v10.16.0

>npm --version
6.9.0
  • 注意:RxJSが6系から書き方が大きく変わった。今回はinstall時にバージョンを指定しなかったので、現時点の最新の6系がターゲットとなった。バージョンを限定したい場合は、npm install時に指定する。

構築

mkdir rxjs_test

cd rxjs_test

npm init -y

## 導入
npm install --save-dev typescript
npm install --save rxjs
npm install --save @types/node

## ファイルの準備
touch tsconfig.json
mkdir src
touch src/app.ts
tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2017",
    "sourceMap": true,
    "types" : ["node"]
  },
  "exclude": [
    "node_modules"
  ]
}

バージョン確認

npm list --depth=0
+-- @types/node@12.0.7
+-- rxjs@6.5.2
`-- typescript@3.5.1

確認したい実装の記述

src/app.ts

// RxJS v6+
import { of, Observable, throwError } from 'rxjs'
import { map, take, mergeMap, catchError } from 'rxjs/operators'

// ** 簡単な例

of(1,2,3).pipe(
    take(2),
    map((n) => n ** 2)
).subscribe(n => {
    console.log(n);
});

console.log('--------------------------------------------------');

// ** 複雑な例

// エラーを返しうるなんらかのAPIの模倣
function someApi(n: number): Observable<string> {
    if (n === 0) {
        return throwError('zeroはダメ');
    } else if (n < 0) {
        return of('ng');
    }

    return of('ok');
}

// 引数に属性を付けて返すなんらかのAPIの模倣
function someApi2(s: string): Observable<string> {
    return of(s + '@@@');
}

// ユーザの入力値の模倣
const userInput = of(1,3,-1, 0, 2);

userInput.pipe(
    mergeMap(n => someApi(n)),
    // someApiでのエラー時に、subscribeのエラー処理にフローを移す場合はcatchErrorをコメントアウトする
    catchError(error => of('catch_error')),
    mergeMap(someApiResult => {
        // someApiの結果によってsomeApi2の呼出しを分岐する
        if (someApiResult === 'ok') {
            return someApi2(someApiResult);
        }else if(someApiResult === 'catch_error') {
            // なんらかのエラー処理
            console.log('catched');
        }
        // throwErrorとしないことで、正常系として後続処理を行う(後続処理はnullチェックが必要になる)
        return of(null);
    })
).subscribe(
  next => {
      if (next !== null)  {
        // someApi2を呼んだときに行う何らかの処理
        console.log(next)
      }
  },
  error => console.log('error.' + error),
  () =>  console.log('complete.')
);

ビルドと実行

# ビルド(./src/app.jsができる)
./node_modules/.bin/tsc
# 実行
node ./src/app.js

# windows コマンドプロンプトの場合、以下でビルドからの実行
.\node_modules\.bin\tsc && node .\src\app.js

# windows powershellの場合、以下でビルドからの実行
.\node_modules\.bin\tsc ; node .\src\app.js

実行結果

1
4
--------------------------------------------------
ok@@@
ok@@@
catched
complete.
4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7