Amrmsmb
Amrmsmb

Reputation: 11406

How to use Single vs Observables

I created an example to see the difference between Single and Observable. the below posted example does not work. Also I can't see any difference between Observable and Single.

How do the below examples work?

Code:

public static void main(String[] args) {

    Single<List<List<Person>>> observables = Single.just(Main.getPersons());
    observables
    .flatMap(ll->Observable.fromIterable(ll)
            .concatMap(p->Observable.fromIterable(p))
                    .map(s->s.getAge()))
    .observeOn(Schedulers.io())
    .subscribe(new SingleObserver() {

        @Override
        public void onError(Throwable arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSubscribe(Disposable arg0) {
            // TODO Auto-generated method stub
            System.out.println("onSubscribe: " + arg0);
        }

        @Override
        public void onSuccess(Object arg0) {
            // TODO Auto-generated method stub
            System.out.println("onSuccess: " + arg0);
        }
    });

private static <T> Observable<T> toObservable(T s) {
    return Observable.just(s);
}
private static List<List<Person>> getPersons() {
    return Arrays.asList(
            Arrays.asList(new Person("Sanna1", 59, "EGY"), new Person(null, 59, "EGY"), new Person("Sanna3", 59, null)),
            Arrays.asList(new Person("Mohamed1", 59, "EGY"), new Person(null, 59, "EGY")),
            Arrays.asList(new Person("Ahmed1", 44, "QTR"), new Person("Ahmed2", 44, "QTR"), new Person(null, null, "QTR")),
                    Arrays.asList(new Person("Fatma", 29, "KSA")),
                    Arrays.asList(new Person("Lobna", 24, "EGY")));
}
}

Upvotes: 1

Views: 426

Answers (1)

akarnokd
akarnokd

Reputation: 70007

Single is for emitting one object and Observable is to emit zero or many objects. An object could be an string, a list, or any composite class you define. Their respective JavaDocs should give some overview about them:

In your learning example, you have to turn the sequence back into a Single if you want to consume it via the SingleObserver. You have many age numbers so you can just apply toList to get them all:

observables
.flatMap(ll -> 
     Observable.fromIterable(ll)
     .concatMap(p -> Observable.fromIterable(p))
     .map(s -> s.getAge())
     .toList()   // <--------------------------------------------------
)

Upvotes: 2

Related Questions