LoginSignup
1
0

More than 5 years have passed since last update.

RxJS Observableの作成 (2)  Observable.from の使い方

Last updated at Posted at 2018-05-23

用途

Observable.fromは、配列などのイテレータブルなオブジェクトやObservable、Promise等から新しいObservableを作成します。

基本的な使い方

Observableを作成する方法の一つとしてよく使用されるオペレーターです。
配列などのイテレータブルなオブジェクトからだけでなく別のObservableやPromiseから作成することが出来ます。
また、文字列を指定すると一文字づつ値を流すObservableを作成することが出来ます。

// 配列からObservableを作成
Rx.Observable.from([1,2,3]).subscribe(x => {
  console.log(x);
});

// 結果
// 1
// 2
// 3


// 文字列からObservableを作成
Rx.Observable.from('foo').subscribe(x => {
  console.log(x);
});

// 結果
// f
// o
// o


// PromiseからObservableを作成
Rx.Observable.from(new Promise((resolve, reject)=>{
  setTimeout(resolve, 100, 'foo');
})).subscribe(x => {
  console.log(x);
});

// 結果
// foo

ES6 stackblitz
TypeScript stackblitz

他のオペレーターとの組み合わせ

mapを使って税込み価格を取得

Rx.Observable.from([100, 250, 365])
  .map((n) => {
    return Math.floor(n * 1.08)
  })
  .subscribe(x => {
    console.log(x);
  }
);

// 結果
// 108
// 270
// 394

APIから取得したデータをmapを使って必要なデータのみ抜き出す。

APIからのデータの取得にはaxiosを使っています。
axios

github APIから「tom」を含んだユーザーを取得し、responseの中からユーザー情報(items)のみを抽出する。

Rx.Observable.from(axios.get('https://api.github.com/search/users?q=tom'))
  .map(x => x.data.items)
  .subscribe(res => {
    console.log(res)
  }
)

// 結果
// items[]

ES6 stackblitz
TypeScript stackblitz

1
0
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
1
0