简体   繁体   中英

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 Comment s.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM