Héctor
Héctor

Reputation: 26054

Mapping Observable<Something> to Observable<Void>

I want to perform task 1 and then task 2 with no need to combine their emitted items. I have this:

interface Service {
    Observable<Something> doTask1();
    Observable<SomethingElse> doTask2();
}

Is it a good approach to make them return Observable<Void> in order to merge them? Both tasks are independents, so the first may be return an empty Observable but the second one has to be executed anyway.

public Observable<Void> doTasks() {
    Observable.merge(service.doTask1(), service.doTask2());
}

If so, is there any "correct" way to map an Observable<Something> to Observable<Void>? I'm doing it like this:

public class TaskService implements Service {
    public Observable<Void> doTask1() {
        return getSomething().map(new Func1<Something, Void>() {
                    @Override
                    public Void call(Something something) {
                        return null;
                    }
                });
    } 
}

Any advise will be appreciated.

Upvotes: 3

Views: 2389

Answers (1)

yosriz
yosriz

Reputation: 10267

Mapping values to Void is a valid way, but, RxJava introduced Completable, which is a variant of Observable that do not emit items, but just completion and error notification. You can use it here,as you don't care about the emitted values, then you'll get cleaner API, and also wouldn't need to map the values to mean less ones.

public Completable doTasks() {    
    Completable.merge(service.doTask1().toCompletable(), service.doTask2().toCompletable());
}

Upvotes: 2

Related Questions