Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 930
manabreak Avatar asked Mar 12 '26 20:03

manabreak


1 Answers

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;
    }
}
like image 50
Pavan Kumar Avatar answered Mar 14 '26 10:03

Pavan Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!