Reputation: 16384
I use regular observable
(not observableArray
), which keeps an array of elements, something like this:
public arrayOfItems: IArrayItem[];
public arrayOfItems$: BehaviorSubject<IArrayItem[]> = new BehaviorSubject<IArrayItem[]>(null);
public setArrayOfItems(arrayOfItems: IArrayItem[]): void {
this.arrayOfItems = arrayOfItems;
this.arrayOfItems$.next(arrayOfItems);
}
public getArrayOfItems(): Observable<IArrayItem[]> {
return this.arrayOfItems$.asObservable();
}
And I'd like to implement a getSingleItemFromArray
method, which should return a single element from arrayOfItems$
and I'd like to get it asObservable
too. Something like this (pseudocode):
public getSingleItemFromArray(): Observable<IArrayItem> {
return this.arrayOfItems$.find(item => item.condition).asObservable();
}
If it is possible, please, point me to the right direction to implement it.
Upvotes: 3
Views: 2193
Reputation: 96899
Since arrayOfItems$
is an instance of BehaviorSubject
you can use one of the following depending on your use-case:
If you want to just replay the single value you can use:
return arrayOfItems$.take(1)
This emits the value cached by the BehaviorSubject
and ends the chain with a proper complete
notification thanks to take(1)
.
Note that you don't have to use asObservable
because each operator returns an Observable.
You can actually get the value stored inside BehaviorSubject
and return in wrapped with an Observable:
const val = arrayOfItems$.getValue();
return Observable.of(val);
I'd personally use the first option because it feels more "Rx".
Upvotes: 3
Reputation: 41427
use Observable.of
to converts argument to an observable sequence.
import { of } from 'rxjs/observable/of';
public getSingleItemFromArray(): Observable<IArrayItem> {
let item: IArrayItem = this.arrayOfItems$.find(item => item.condition);
return Observable.of(item )
}
Upvotes: 3