Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to the type of Observable<T[]>

I want to convert an array to type Observable<T[]> and have used the rxjs method "from". But it returns Observable<T>, Is there a way to convert an array to Observable<T[]>?

Player: Observable<T[]>;

convert(){
let tempArr:T[] = Object.values(data) as T[];
let Obsobj = from(tempArr);
this.Player = Obsobj;
}

This is the error message I got, Observable<T> is not assignable to type Observable<T[]>

EDIT

Even though using following code snippet return type isn't as expected.

let $sub = new Subject<Array<T>>();
$sub.next(tempArr);
this.Player$ = $sub.asObservable();

Since I want the return observable type to be as follows.

Observable {_isScalar: false, source: Observable, operator: MapOperator}

but returned the following.

Observable {_isScalar: false, source: Subject}

EDIT #2

complete code snippet.

Player: Observable<B[]>;

convert(data: Dictionary<B>){
   let tempArr:B[] = Object.values(data) as B[];
   let $sub = new Subject<Array<B>>();
   $sub.next(tempArr);
   this.Player$ = $sub.asObservable();
}

What is the issue here? Any help?

like image 533
Ramzan Dieze Avatar asked Jul 15 '19 02:07

Ramzan Dieze


People also ask

How do you map an array to an observable?

To convert from array to observable you can use Rx. Observable. from(array) . To convert from observable to array, use obs.

What is an observable array?

ObservableArray is an array that allows listeners to track changes when they occur.

How do you remove an element from an observable array?

pop() — Removes the last value from the array and returns it. unshift( value ) — Inserts a new item at the beginning of the array. shift() — Removes the first value from the array and returns it. reverse() — Reverses the order of the array and returns the observableArray (not the underlying array).


1 Answers

Observable.from Documentation: For arrays and iterables, all contained values will be emitted as a sequence! So your items will always be emitted as T and not T[]

For Observable<T[]> do either of the following:

$sub = new Subject<Array<T>>();
this.Player = $sub.asObservable();

OR

this.Player = of(array);

OR

Observable.create((observer) => {observer.next(array)})
like image 172
Ruraloville Avatar answered Sep 19 '22 14:09

Ruraloville