1
votes

I want to create an Observable that subscribes to another Observable and yields true on success and false on error.

This is my solution:

new Observable ((observer: Observer<boolean>) => {
  obs().subscribe (() => {
    observer.next (true);
  }, error => {
    observer.next (false);
  })
});

But I think there must be an easier solution without "new Observable". Something like:

obs().pipe (
  map (() => true),
  catchError(() => of(false))
);

But that leaves just typescript errors:

error TS2322: Type 'Observable' is not assignable to type 'boolean | Observable'.

Type 'Observable' is not assignable to type Observable'.

Type 'boolean | {}' is not assignable to type 'boolean'.

Type '{}' is not assignable to type 'boolean'.

I am using: rxjs 5.5.2 typescript 2.4.2

2

2 Answers

1
votes

Maybe it was a problem with imports, now this works:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';

obs ().map (() => true).catch (() => Observable.of (false));
0
votes

You could try catching the exception and returning false

obs().catch(()=> of(false))
     .map(value=>{
         if(!value){
             return false;
         }
         return true;
     );

if the value is not truthy then return false, if it is truthy return a new observable of true.