Viktor
Viktor

Reputation: 561

Java rx - should you use Single<List<Item>> or rather Observabe<Item>

I have a question regarding which style of java rx better to use. Let's say you have a web service, that returns a List of items, which we will represent by a list. Now most tutorials seem to handle this by emitting single values through observable, for example:

 Observable<Todo> todoObservable = Observable.create(new ObservableOnSubscribe<Todo>() {
        @Override
        public void subscribe(ObservableEmitter<Todo> emitter) throws Exception {
            try {
                List<Todo> todos = RxJavaUnitTest.this.getTodos();
                for (Todo todo : todos) {
                    emitter.onNext(todo);
                }
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        }
    });

However you could handle the situation through Single, emitting a list:

Single.create(new SingleOnSubscribe<List<Todo>>() {
        @Override
        public void subscribe(SingleEmitter<List<Todo>> emitter) throws Exception {
            List<Todo> todos = RxJavaUnitTest.this.getTodos();
            emitter.onSuccess(todos);
        }
    })

Is there an advantage to emit per item over the whole list? It seems to me that mostly you would want to combine the items back to the list in the ui...

Upvotes: 2

Views: 480

Answers (1)

Jojo Narte
Jojo Narte

Reputation: 3104

Single would make more sense if you're getting the data from the webservice. You're only expecting one instance of response mostly.

Observable would only be beneficial for you if you expect the web service request to be a stream. For most Single would give you what you need with less overhead.

Upvotes: 2

Related Questions