RxJava 访问项目下游
RxJava access item downstream
我将几个 rx
运算符链接在一起来执行多项任务。我需要从下游父流中的对象访问一个字段。
即。如何访问 channel.uid
下游?
createThing(panel) // Observable<~>
.flatMapSingle(
channel -> {
return createOrUpdateItem(channel);
})
.flatMapCompletable(
item -> {
return linkItemToChannel(item.name, /* need access to channel.uid here */ channel.uid);
});
使用 Observable.flatmap(Function mapper, BiFunction resultSelector) (or Flowable 版本)。例如:
createThing(panel) //I assume that this method returns Observable
.flatMap(channel -> createOrUpdateItem(channel).toObservable(),
(channel, item) -> linkItemToChannel(item.name, channel.uid).toObservable())
.toCompletable();
flatMapSingle
或 flatMapCompletable
没有类似的覆盖方法,因此您必须将 Single
和 Completable
转换为 Observable
(或 Flowable
).或者您可以编写自己的运算符 ;)
添加到@maxost 的答案,在这里你可以避免最后的 toCompletable()
和 toObservable()
:
createThing(panel)
.flatMap(new Function<Channel, ObservableSource<? extends Item>>() {
@Override public ObservableSource<? extends Item> apply(Channel channel) throws Exception {
return createOrUpdateItem(channel).toObservable();
}
},
new BiFunction<Channel, Item, Completable>() {
@Override public Completable apply(Channel channel, Item item) throws Exception {
return linkItemToChannel(item.name, channel.uid);
}
}
)
.ignoreElements() // converts to Completable
Lambda:
createThing(panel)
.flatMap(channel -> createOrUpdateItem(channel).toObservable(),
(channel, item) -> linkItemToChannel(item.name, channel.uid))
.ignoreElements() // converts to Completable
我将几个 rx
运算符链接在一起来执行多项任务。我需要从下游父流中的对象访问一个字段。
即。如何访问 channel.uid
下游?
createThing(panel) // Observable<~>
.flatMapSingle(
channel -> {
return createOrUpdateItem(channel);
})
.flatMapCompletable(
item -> {
return linkItemToChannel(item.name, /* need access to channel.uid here */ channel.uid);
});
使用 Observable.flatmap(Function mapper, BiFunction resultSelector) (or Flowable 版本)。例如:
createThing(panel) //I assume that this method returns Observable
.flatMap(channel -> createOrUpdateItem(channel).toObservable(),
(channel, item) -> linkItemToChannel(item.name, channel.uid).toObservable())
.toCompletable();
flatMapSingle
或 flatMapCompletable
没有类似的覆盖方法,因此您必须将 Single
和 Completable
转换为 Observable
(或 Flowable
).或者您可以编写自己的运算符 ;)
添加到@maxost 的答案,在这里你可以避免最后的 toCompletable()
和 toObservable()
:
createThing(panel)
.flatMap(new Function<Channel, ObservableSource<? extends Item>>() {
@Override public ObservableSource<? extends Item> apply(Channel channel) throws Exception {
return createOrUpdateItem(channel).toObservable();
}
},
new BiFunction<Channel, Item, Completable>() {
@Override public Completable apply(Channel channel, Item item) throws Exception {
return linkItemToChannel(item.name, channel.uid);
}
}
)
.ignoreElements() // converts to Completable
Lambda:
createThing(panel)
.flatMap(channel -> createOrUpdateItem(channel).toObservable(),
(channel, item) -> linkItemToChannel(item.name, channel.uid))
.ignoreElements() // converts to Completable