Reputation: 1485
I'm still learning RxJava and I wanted to know if there was another way to do what I want.
I have the following code, and it works:
apiManager.getChannelListByRegion(region)
.observeOn(scheduler)
.map(new Func1<ChannelList, List<ChannelList.Channel>>() {
@Override
public List<ChannelList.Channel> call(ChannelList channelList) {
if (params.getGenre() == 0) {
return channelList.getChannels();
} else {
List<ChannelList.Channel> filteredList = new ArrayList<>();
for (ChannelList.Channel channel : channelList.getChannels()) {
if (Integer.parseInt(channel.getGenreId()) == params.getGenre())
filteredList.add(channel);
}
return filteredList;
}
}
})
.subscribe(new SuccessCallback<>(callback), new ErrorCallback(callback));
Some explanantion - The ChannelList is a POJO representing some JSon from an external service. I have no control over the structure of this JSon.
ChannelList contains an embedded List which I want and I am able to get it via the map() operator quite easily assuming no filtering of the list.
If I need to filter however, I resorted to a loop over its contents and checked for the filtering condition.
Is there a way to better filter? I'm assuming I would need to create another Observable that emits the List contents and provide a function but I'm not sure how to do that.
Upvotes: 0
Views: 128
Reputation: 2504
I can show you how to rewrite your code using only FP and reactivex. It is rather matter of taste if it is simpler. I will use lambdas to make the code simpler to understand.
apiManager.getChannelListByRegion(region)
.observeOn(scheduler)
.flatMap(channelList->Observable.from(channelList.getChannels()))
.filter(channel->params.getGenre() == 0 || Integer.parseInt(channel.getGenreId()) == params.getGenre())
.toList()
.subscribe(new SuccessCallback<>(callback), new ErrorCallback(callback));
As you can see, I first convert ChannelList into Observable of Channel, to later filter it and collect as list.
Upvotes: 1