简体   繁体   中英

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);
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM