0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Hesam
  • 52,260
  • 74
  • 224
  • 365
  • I do not catch your point yet. Do you want to emit each item on the list? – ThaiPD Sep 14 '18 at 14:50
  • Hi @PhanDinhThai. I am modifying my list -as you see in the fist code- in `map` operator. I think this is not good way. So, I want to have another operator - before `map` - in order to modify my List and then pass the list down to `map` operator. Please let me know if I am still not clear. Thanks. – Hesam Sep 15 '18 at 12:36

2 Answers2

0

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.

Habib Okanla
  • 246
  • 2
  • 5
  • Thanks Habib. `doOnNext` is just for instance. I am not sure what operator is good in my case. – Hesam Sep 15 '18 at 12:38
0

(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.

ThaiPD
  • 3,503
  • 3
  • 30
  • 48