3

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.

2 Answers 2

3

Since arrayOfItems$ is an instance of BehaviorSubject you can use one of the following depending on your use-case:

  1. 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.

  2. 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".

Sign up to request clarification or add additional context in comments.

2 Comments

I can't figure out what is the correct way of using the first method (my fault, I'm sure that it should work), but the second way works perfectly, thanks! Upvote and accept!
@CommercialSuicide If you're using RxJS 5.5 you need to use pipe like arrayOfItems$.pipe(take(1))
3

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

1 Comment

I really like @martin answer, but thanks for your answer too, upvote!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.