1
votes

I sometimes use RxJava to write in a more functional style for some complex filterings, mappings and so on (I know that this is not what it's made for, and I would be happy to use Kotlin or Java 8 for that, but I can't (I'm on Android so, stuck to 6).

However, when you try to "extract" the actual objects out of the Observable, you always need to write .toList().toBlocking().singe()

E.g. (not so complex, but you get the idea):

final List<CashRegister> cashRegisters = cashRegisterData.getCashRegisters();

return Observable.from(cashRegisters)
        .map(CashRegister::getName)
        .toList()
        .toBlocking()
        .single();

As you can see, "converting" the Observable into a list needs more lines than the actual mapping I want to perform.

Is there a way of doing this without the toList().toBlocking().single() chain?

2
I would be happy to use Kotlin or Java 8 for that, but I can't: you are using Java 8 already. So just use cashRegisters.stream().map(CashRegister::getName).collect(toList())JB Nizet
@JBNizet oh sorry, I wasn't clear. I'm on android and I'm using retrolambda for the :: and lambdasLovis
@JBNizet thanks again for your input. I didn't want to add another library (since it's not really necessary) otherwise I would probably use streams backport for android.Lovis
I'll probably just write a static methodLovis
@JBNizet Guava has a ridiculous method count, so it's not recommended for Android (65536 method limit sucks)EpicPandaForce

2 Answers

2
votes

You can use IxJava to perform the same operation:

final List<CashRegister> cashRegisters = cashRegisterData.getCashRegisters();

return ix.Ix.from(cashRegisters)
    .map(CashRegister::getName)
    .toList();
1
votes

With RxJava one has to change the way they think about using Observables. The observable operation chain should be treated more like a math formula, not a sequence of operations. So, instead of trying to get results out of observable, try to figure out what you want to do with that list.

In RxJava, prefer not to extract the observable values, but to subscribe to them:

someObservable.subscribe(result -> {
    // Now do your deed with the result
    // for example:
    someAdapter.setData(result);
    someAdapter.notifyDatasetChanged();
})

I'd kindly recommend to read the documentation on How to use RxJava to understand the idea.