简体   繁体   English

rxjava:flatmap 和 map 的区别

[英]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.第一个简单地重复将对象包装成Single ,而第二个将其映射到自身。 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.阅读 'flatMap()' 和 'map()':第一个将每个值转换为不同值的 observable,第二个将每个值转换为不同的值。

You can represent for your self a flatMap operator like a sequence of two other operator map and merge .您可以为自己表示一个flatMap运算符,就像其他两个运算符mapmerge的序列一样。

Map will convert your source item to Observable that emit a value based on the function inside of map . Map将您的源项目转换为 Observable,它根据map内部的函数发出一个值。 At this point merge will help to put together every item that emitted by each of your new observables, not the source one.在这一点上, merge将有助于将每个新 observables 发出的每个 item 放在一起,而不是源 observables。

There is a good illustration on that book https://www.manning.com/books/rxjava-for-android-developers那本书上有一个很好的插图https://www.manning.com/books/rxjava-for-android-developers

map with merge together合并在一起的地图

To simplify this code was introduced flatMap operator为了简化这段代码,引入了flatMap操作符

only flatMap只有平面地图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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