For a Web-Application written with Angular2 in TypeScript, I need to work with RxJs Observables.
As I never used rxjs before and I am new to reactiveprogramming in general, I sometimes have some difficulties finding the right way to do some specific things.
I am now facing a problem. where I have to convert an Array<Observable<T>> into an Observable<Array<T>>.
I'll try to explain it with an example:
- I have an
Observable, which gives me a list ofUsers(Observable<Array<User>>) - The
User-class has a functiongetPostsreturning anObservable<Array<Post>>. - I need to map the
Observable<Array<User>>to anObservable<Array<Post>>to evaluate all thePosts inside theonNextfunction.
I can easily map from Observable<Array<User>> to Observable<Array<Observable<Array<Post>>>> using
map((result : Array<User>) => result.map((user : User) => user.getPosts()))
and I can flatten an Array<Array<Post>> into an Array<Post>.
However I just can't find the correct way to map the Observable<Array<Observable<Array<Post>>>> into an Observable<Array<Array<Post>>>
Until now i used the combineLatest function together with flatMap.
To me it seemed to work and the editor i used (Atom editor) did not show any error. However now I use Netbeans, which shows me an error in this code. Also compiling the code using "tsc" results in the following errors:
Argument of type '(result: Post[]) => void' is not assignable to parameter of type 'NextObserver<[Observable<Post>]> | ErrorObserver<[Observable<Post>]> | CompletionObserver<[...'.
Type '(result: Post[]) => void' is not assignable to type '(value: [Observable<Post>]) => void'.
So my question is:
How can I "flatten" an Array of Observables into an Array?
getPostsmethod correspond to? Does it load the posts of a specific user?