Reputation: 4391
Is there any difference between this:
public Observable<List<MessageDb>> getLastXMessages(int x, String userToGetMessagesFrom){
return MainApplication.getInstance().getRiotXmppService().getRiotConnectionManager().getConnectedUser()
.flatMap(connectedUser -> {
QueryBuilder qb =
...
...
return Observable.just(qb.list());
});
}
or this
public Observable<List<MessageDb>> getLastXMessages(int x, String userToGetMessagesFrom){
return MainApplication.getInstance().getRiotXmppService().getRiotConnectionManager().getConnectedUser()
.map(connectedUser -> {
QueryBuilder qb =
...
...
return qb.list();
});
}
Is there any preferable solution or both just works fine.
Upvotes: 1
Views: 1112
Reputation: 12087
Sure both work fine. If you are not planning to do stuff asynchronously then I'd prefer map
because it carries less overhead than flatMap
. Seeing as it looks like there are network calls involved in your example (?) that overhead would probably be insignificant.
Upvotes: 2
Reputation: 3372
FlatMap behaves very much like map, the difference is that it returns an observable itself, so its perfectly suited to map over asynchronous operations. Map does not have to emit items of the same type as the source Observable.
In the practical sense, Map just makes a transformation over the chained response (not returning an Observable); while FlatMap returns an Observable, that is why FlatMap is recommended if you plan to make an asynchronous call inside the method, So:
Map returns an object of type T
FlatMap returns an Observable.
Upvotes: 1