I'm playing with RxJava in Android. I'm trying to get the response of places from the server. Everything works fine:
Here is my Retrofit interface:
@GET("/some/path")
Observable<Response> search(@QueryMap Map map);
Here is how I handle this:
endpointService.search(requestMap)
.onErrorReturn(throwable -> {
L.e(TAG, "problems");
return null;
})
.subscribe(rxBus::send);
As you may see, I post a event (RxBus) to interested parties, in this case, a fragment:
rxBus.register(Response.class)
.subscribe(event -> {
L.d(TAG, "Received search response");
});
For now it works. I'm not shure, this "idea" of handling REST calls won't finish in a disaster (I'm new into RxJava), but for now it looks allright...
Anyways - this response is huge. I only need a list of names and addresses. And this response gives me a huuuge JSON with a lot of additional data.
My idea is to change this with map
(or flatMap
, I still have problems with knowing the difference).
I've implemented something like
.map(event -> {
List<SearchItem> list = new ArrayList<>();
for (Response r : event.getItems) {
list.add(new Item(r.getName, r.getAddress));
}
return list;
}
)
And it works, however I'm not sure if foreach-ing isn't a bit too "oldschool". IDE says that I cant use collect call
however I've never used it, and the autocorrection makes things even worse :)
So - am I handling this whole thing in a right way?
EDIT:
I modified my code:
rxBus.register(Response.class)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.map(event -> event.getResponse().getList())
.flatMap(Observable::from)
.map(v -> new SearchItem(v.getName(), v.getAddress())
.toList()
.subscribe(event -> {
L.w(TAG, "Stuff happens");
});
I have no idea what happened, but this code no longer works. Well - kinda. Without .toList()
it launches that Log a number of times. However with - nothing happens. Am I doing something wrong?
>` to an `Observable`, and (3) `map` each of them to an `Item`.