A Jar of Clay
A Jar of Clay

Reputation: 6298

Subscribe callback not called when empty Observable returned

I expect the subscribe callback to be called when returning an empty Observable, similar to Promise.resolve([]):

import { EMPTY } from 'rxjs';

function funcToTest(): Observable<any[]> {
  return EMPTY;
};

test('returns empty array', (done) => {
  funcToTest().subscribe(() => {
    done();
  });
});

Instead, it returns this error:

Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

Upvotes: 0

Views: 1002

Answers (1)

A Jar of Clay
A Jar of Clay

Reputation: 6298

Observables act differently to promises. The RxJS EMPTY Observable doesn't call the 'success' callback, only the 'complete' callback. The done function should be called in 'complete' rather than in 'success':

funcToTest().subscribe({
  success()  { /* Called when 'x' is returned, e.g. after the subscriber calls 'next' */ },
  error(err) { /* Called on an error. */ },
  complete() {
    /* Called after the subscriber calls 'complete'. No more values can be returned */
    done();
  }
});

See the examples in the docs: https://rxjs-dev.firebaseapp.com/guide/observable

Upvotes: 3

Related Questions