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을 리턴하는 메소드가 책을 반환하기를 원할뿐입니다. 그렇게하기 전에 일부 필드를 재귀 적으로 '해석'해야합니다. –
특히, 나는 그것이 완전하게 형성되기 전에 그 책이 관찰 가능한 것으로부터 방출되는 것을 원하지 않는다. 나는 resolver로부터'getBook (name)'을 구독하고 있는데, 데이터가로드 될 때까지 페이지 로딩을 원하지 않는다. –
위의 구조를 취하고'.toArray()'를 끝에 추가 할 수있다. 앞으로 나아 가기 전에 모든 결과를 배열로 모을 것입니다. 마녀 후에'.map (...) '을 사용하여 필요에 따라 재조합 할 수 있습니다. – Graztok