Anirudha Mahale
Anirudha Mahale

Reputation: 2596

Subscribe to child Observable's Subscribe in RxJS

I have emitEvenFrom method that takes one argument and emits the event.

when the argument is false it doesn't emit any event though am directly returning an observable of type of.

import { Observable, Observer, of } from 'rxjs'

function emitEventFrom(thisObservable: boolean): Observable<string> {
    return Observable.create(function (observer: Observer<String>) {
        if (thisObservable) {
          observer.next('thisObservable')
          observer.complete()
        } else {
          // Returning Rx.Observable.of()
          return of('Other observable')
        }
    })
}

emitEventFrom(false).subscribe({
    next: (value) => console.log(value),
    error: (error) => console.log(error)
})

Why the subscribe ins't called on of Observable when I have returned it.

Instead I have to subscribe to the that observable explicitly and pass on the event to the parent observable then only it works. Doing this it increases the code that I have write.

function emitEventFrom(thisObservable: boolean): Observable<string> {
    return Observable.create(function (observer: Observer<String>) {
        if (thisObservable) {
            observer.next('thisObservable')
            observer.complete()
        } else {
            // Returning Rx.Observable.of()
            of('Other observable').subscribe({
                next: (value) => observer.next(value),
                error: (error) => observer.error(error)
            })
        }
    })
}

Am I doing something wrong? or Show me a better way.

Upvotes: 1

Views: 497

Answers (1)

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

You need to return of from your function instead of inside of Observable.create

Here is a working blitz

Change your emitEventFrom to following

function emitEventFrom(thisObservable: boolean): Observable<string> {
  if (thisObservable) {
    return Observable.create(function (observer: Observer<String>) {
      observer.next('thisObservable')
      observer.complete();
    });
  } else {       
    return of('Other observable');
  }
}

Upvotes: 1

Related Questions