2

I don't understand why I can do

ForkJoin(service.Obs1(), service.Obs2()).subscribe

But if I refactor my code such that I add a method to my service class that returns ForkJoin(this.Obs1(), this.Obs2()), such as for example

updateWhatever(): Observable<[string, string]> {
return forkJoin([
  this.Obs1(),
  this.Obs(2)
]);}

Then if I do service.updateWhatever().subscribe(res => //handle res[]., it throws the error

You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

Why won't this work? One should be able to refactor in such a fashion. What am I missing? I realize it's returning an array of observables, but why should the function call not handle this?

Maybe my question is, how does one handle a method that returns a forkJoin ?

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Axel
  • 867
  • 6
  • 9

2 Answers2

2

Specific to Rxjs 5 or earlier:

forkJoin doesn't expect an Array of Observable(s). It expects source(s) of type SubscribableOrPromise

You'll have to do it like this:

updateWhatever() {
  return forkJoin(
    this.Obs1(),
    this.Obs(2)
  );
}
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • 3
    This is not true, at least with RxJS 6, see https://rxjs-dev.firebaseapp.com/api/index/function/forkJoin – Picci Oct 30 '18 at 08:23
  • The point is that forkJoin is defined with a rest parameter, and not just one normal array type argument. The `...` before `sources` indicates this. – ShamPooSham Oct 30 '18 at 08:49
  • I Agree with @Picci , we can pass array of observable in forkJoin also – Jameel Moideen Oct 30 '18 at 15:48
1

It's possible to return a forkJoin.In your code the problem is Obs1 and Obs2 are not an observable,promise,array or Iterable.That's why rxjs throwing an error.

I Agree @Picci comment, we can pass array of observable in forkJoin also

Sample Code

const a = stream('a', 200, 3, 'partial');
const b = stream('b', 500, 3, 'partial');

someMethod().subscribe((response)=>{
  console.log(response);
});

someMethodFkAsAnArray().subscribe((response)=>{
  console.log(response);
});


function someMethod(){
  return forkJoin(a, b);
}

function someMethodFkAsAnArray(){
  return forkJoin([a, b]);

}

StackBlitz Demo using RxJs 5.5.2

Jameel Moideen
  • 7,542
  • 12
  • 51
  • 79