manabreak
manabreak

Reputation: 5597

RxJava: Can a result be split into two different observables?

I have an observable that emits a single object which has two fields, something like this:

public class Details {
    private Link link;
    private List<Comment> comments;
}

Observable<Details> detailsObservable = ...;

Now, I was wondering: can this observable be somehow split into two observables? What I'd like to do is to have a subscriber listen for the link and another one to listen for Comments.

Upvotes: 3

Views: 663

Answers (1)

Pavan Kumar
Pavan Kumar

Reputation: 4810

You can use map method to achieve that. Example code shared below, let me know if it helps.

public static void main(String[] args) {
    Observable<Details> dObs = Observable.just(new Details("a", "c"));
    Observable<String> lObs = dObs.map(d -> d.link);
    Observable<String> cObs = dObs.map(d -> d.comments);
    lObs.subscribe(s -> System.out.println(s));
    cObs.subscribe(s -> System.out.println(s));
}


static class Details {
    String link;
    String comments;

    public Details(String link, String comments) {
        this.link = link;
        this.comments = comments;
    }
}

Upvotes: 2

Related Questions