Emilien Brigand
Emilien Brigand

Reputation: 10971

rxjava: difference between flatmap and map

I would like to know if there is any difference in the behavior between those both methods or if it's just a matter of style:

private Single<JsonObject> foo() {
     return Single.just(new JsonObject()).flatMap(next -> Single.just(next));
}

private Single<JsonObject> bar() {
     return Single.just(new JsonObject()).map(next -> next);
}

Upvotes: 0

Views: 2172

Answers (2)

Dmitriy Mitroshin
Dmitriy Mitroshin

Reputation: 26

You can represent for your self a flatMap operator like a sequence of two other operator map and merge.

Map will convert your source item to Observable that emit a value based on the function inside of map. At this point merge will help to put together every item that emitted by each of your new observables, not the source one.

There is a good illustration on that book https://www.manning.com/books/rxjava-for-android-developers

map with merge together

To simplify this code was introduced flatMap operator

only flatMap

Upvotes: 0

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

There is no difference in behavior as both are pointless operations. The first simply repeats wrapping the object into a Single, while the second maps it to itself. You would never have a reason to do either.

Read up on 'flatMap()' and 'map()': the first turns each value into an observable of different values, the second turns each value into a different value.

Upvotes: 1

Related Questions