iberbeu
iberbeu

Reputation: 16185

Return a single object after Observable is complete

I have an Observable with a couple of elements (fonts)

myFontsObservable = Observable.of<Font>(new Font("font1"), new Font("font2"));

Now I want to subscribe this Observable, process all the Fonts and register them in a Document and just after it finishes processing all of them, return the Document

public registerFonts(myFontsObservable): Observable<Document> {
    doc = new Document();
    myFontsObservable.subscribe(
        font => doc.register(font);
        (err) => {},
        () => return Observable.of(doc);
    );
    // I need to return something here too
}

This code won't compile because I need to return something also outside the subscribe. But if I return something there then when I call registerFonts(...) I get the wrong value because it is not yet complete

How can I do this?

Upvotes: 0

Views: 778

Answers (2)

Picci
Picci

Reputation: 17752

You may try something along these lines

public registerFonts(myFontsObservable): Observable<Document> {
    return myFontsObservable
           .reduce((doc, font) => {
              doc.register(font);
              return doc
           }, new Document())
}

Upvotes: 1

user4676340
user4676340

Reputation:

Use the mergeMap operator (pipeable).

This operator will process the result of the first observable,, and needs to return another observable. I believe this is what you need.

public registerFonts(myFontsObservable): Observable<Document> {
    doc = new Document();
    return myFontsObservable.pipe(
      mergeMap(font => {
        doc.register(font);
        return Observable.of(doc);
      })
    );
}

Upvotes: 0

Related Questions