flatMap
を利用して、このようなパターンを試すことができます。前のイベントが終了すると、flatMap
はそのコールバックによって返されたObservable
で継続します。読みやすさにかなり役立ち、途中でストリームを偵察することができます。
import { Observable } from 'rxjs';
class Demo {
backend = {
// Simulated request
getJSON: (str, demoValue) => Observable.of(demoValue).delay(new Date(Date.now() + 1000))
}
getBook(name) {
this.backend
// Get the book
.getJSON(`${name}/book`, name)
// Get the parts
.flatMap(book => {
// Observable.from() will create an observable event
// for each item in the array
return this.backend
.getJSON(`[Next URL]`, [`${book}/part1`, `${book}/part2`])
.flatMap(parts => Observable.from(parts));
})
// Get the sections
.flatMap(part => {
return this.backend
.getJSON(`[Next URL]`, [`${part}/section1`, `${part}/section`])
.flatMap(sections => Observable.from(sections));
})
// Get the chapters
.flatMap(section => {
return this.backend
.getJSON(`[Next URL]`, [`${section}/chapter1`, `${section}/chapter2`])
.flatMap(chapters => Observable.from(chapters));
})
// etc.
.subscribe(console.log)
}
}
let t = new Demo();
t.getBook('cool');
この出力:
cool/part1/section1/chapter1
cool/part1/section1/chapter2
cool/part1/section2/chapter1
cool/part1/section2/chapter2
cool/part2/section1/chapter1
cool/part2/section1/chapter2
cool/part2/section2/chapter1
cool/part2/section2/chapter2
私はあなたがで取得しているかを見るが、私は本当に本自体のように(観測可能から放出されるだろう、むしろ私がしたいの章、より本の構造の一部である)。私はobservableを返すメソッドが本を返すようにしたいだけです。その前にいくつかのフィールドを再帰的に '解決'する必要があるだけです。 –
特に、完全に形成される前に、この本が観測可能なものから放出されることは望ましくありません。私はリゾルバから 'getBook(name)'を購読していますが、データがロードされるまでページを読み込まないようにします。 –
上記の構造をとり、 '.toArray()'を最後に追加することができます。これにより、前に進む前にすべての結果が配列に集められます。魔女の後には、あなたはそれを再結合するために '.map(...)'を使うことができます。 – Graztok