[英]How to create Observable that emits items once and then onComplete from BehaviorSubject?
I need to create an Observable<T>
from a BehaviorSubject<Observable<T>>
.我需要从BehaviorSubject<Observable<T>>
创建一个Observable<T>
。 The created observable should only emit items once and then call onComplete()
.创建的 observable 应该只发出一次项目,然后调用onComplete()
。
Is there a way to do this?有没有办法做到这一点?
Thanks!谢谢!
Edit编辑
private BehaviorSubject<Observable<T>> subject = BehaviorSubject.create();
public Observable<T> getObservable(){
//return the subject as Observable<T> which emits once and call onComplete()
}
So, you have a BehaviorSubject that emits Observable<T>
s, and from this you want to create an Observable<T>
that only emits the first item of the first Observable emitted by the Subject.因此,您有一个 BehaviorSubject 发出Observable<T>
s,并且您想从中创建一个Observable<T>
,它只发出主题发出的第一个Observable 的第一项。 You could do that like this:你可以这样做:
public Observable<T> getObservableWithJustOneElement(){
return subject.flatMap(new Func1<Observable<T>, Observable<T>>(){
@Override
public Observable<T> call(Observable<T> source) {
return source;
}
})
.take(1);
}
I know it looks a bit weird but it should be doing what you want.我知道它看起来有点奇怪,但它应该做你想做的。 First, the flatMap
flattens the Observable<Observable<T>>
to just an Observable<T>
(it just does not do any mapping in the sense of transforming the elements).首先, flatMap
将Observable<Observable<T>>
扁平flatMap
一个Observable<T>
(它只是在转换元素的意义上不做任何映射)。 Then, the take(1)
makes sure that only one item will be emitted with onNext()
and after that onCompleted()
will be called.然后, take(1)
确保onNext()
只发出onNext()
,然后调用onCompleted()
。
If you had wanted only the items emitted by the first Observable emitted by the Subject, you could have used this instead:如果你只想要由 Subject 发出的第一个 Observable 发出的项目,你可以用这个代替:
public Observable<T> getObservableWithJustOneElement(){
return subject.take(1)
.flatMap(new Func1<Observable<T>, Observable<T>>(){
@Override
public Observable<T> call(Observable<T> source) {
return source;
}
});
}
You can also create an Observable
that emits once from for example a ReplaySubject
or a BehaviourSubject
with the first operator .您还可以创建一个Observable
,例如从ReplaySubject
或BehaviourSubject
使用 第一个 operator发出一次。
return behaviorSubject.pipe(first());
in case you want to return the first item that satisfies certain criteria you can use a predicate as an argument:如果您想返回满足特定条件的第一项,您可以使用谓词作为参数:
const predicate = (result: any): boolean => {
//your test to check the result should return true...
}
return behaviorSubject.pipe(first(predicate));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.