Skip to content
Advertisement

RxJava – Just vs From

I’m getting the same output when using Observable.just vs Observable.from in the following case:

 public void myfunc() {
 //swap out just for from here and i get the same results,why ?
        Observable.just(1,2,3).subscribe(new Subscriber<Integer>() {
            @Override
            public void onCompleted() {
                Log.d("","all done. oncompleted called");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer integer) {
                Log.d("","here is my integer:"+integer.intValue());
            }
        });

    }

I thought just was just supposed to emit a single item and from was to emit items in some sort of list. Whats the difference ? I also noted that just and from take only a limited amount of arguments. So Observable.just(1,2,3,4,5,6,7,8,-1,-2) is ok but Observable.just(1,2,3,4,5,6,7,8,-1,-2,-3) fails. Same goes for from, I have to wrap it in a list or array of sorts. I’m just curious why they can’t define unlimited arguments.

UPDATE: I experimented and saw that just does not take a array structure it just takes arguments. from takes a collection. so the following works for from but not for just:

 public Observable myfunc() {
    Integer[] myints = {1,2,3,4,5,6,7,8,-1,-2,9,10,11,12,13,14,15};
   return  Observable.just(myints).flatMap(new Func1<Integer, Observable<Boolean>>() {
        @Override
        public Observable<Boolean> call(final Integer integer) {
            return Observable.create(new Observable.OnSubscribe<Boolean>() {
                @Override
                public void call(Subscriber<? super Boolean> subscriber) {
                    if(integer.intValue()>2){
                        subscriber.onNext(integer.intValue()>2);

                    }
                }
            });
        }
    });

}

I am assuming this to be the clear difference then, correct ?

Advertisement

Answer

The difference should be clearer when you look at the behaviour of each when you pass it an Iterable (for example a List):

Observable.just(someList) will give you 1 emission – a List.

Observable.from(someList) will give you N emissions – each item in the list.

The ability to pass multiple values to just is a convenience feature; the following are functionally the same:

Observable.just(1, 2, 3);
Observable.from(1, 2, 3);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement