How to pass modified list downstream in RxJava in Android?

102 Views Asked by At

I have following code that works well.

Observable.from(...)
    .map { // List<Object>
        if (My_Condition_is_true) {
            //...
        }
        val newList = getNewListIfConditionIsOkay(it)
        newList.map { item -> toSomethingElse(item) }
    }
    .subscribeBy(myErrorFun) {
        //...
    }

I feel map operator does not looks cool but I have no idea how to fix it. This is what is in my mind.

Observable.from(...)
        .doOnNext {// List<Object>
            if (My_Condition_is_true) {
                //...
                return getNewListIfConditionIsOkay(it)
            }
            return it
        .map { // List<Object>
            it.map { item -> toSomethingElse(item) }
        }
        .subscribeBy(myErrorFun) {
            //...
        }

My Observable returns only a list. What is your recommendation?

2

There are 2 best solutions below

1
On

map is fine. Save doOnNext for side effect tasks, doOnNext actually doesn't return any value, so I don't think your code would even work here.

0
On

(I don't know if I completely understand your idea or not)

As far as I know, currently there no operator allows us to do as you want. So, in order to solve your problem, the way I always try is combine operations.

Please see the details below:

First: a method to get Your List

private List getYourList() {
    // do something here to get your list
    return yourList;
}

Second: A method to get List with condition, remember to use Observable.fromCallable

private Observable<List> getListWithCondition() {
       return Observable.fromCallable(new Callable<List<Employee>>() {
        @Override
        public List<Employee> call() throws Exception {
            // check your condition if needed
            if (My_Condition_is_true) {
              //...
            }
            val newList = getNewListIfConditionIsOkay(it);
            return newList;
        }
    });

}

Finally, do your work by calling function above

public void doYourWork() {
    getListWithCondition().map(new Func1<List<>, Object>() {
        item -> toSomethingElse(item)
    }).subscribe();
}

Please let me know if I'm not get your point correctly, I'll remove my answer. Hope that help.