observablees6-promiseweb-sqlrxjs6

What is an equivalent in rxjs6 of Promise.resolve


I'm trying to resolve after an async call to the websql api. For now I'm returning a Promise and it's working. however, for some reasons of design,I would like to do it with rxjs6 observables. Do you know how to have the same behavior with rxjs ?

Please take in account that tx.executeSql and websqlDatabase.transaction return void and I don't have access to the code of these functions.

Thanks in advance

    return new Promise((resolve, reject) => {
        this.websqlDatabase.transaction(tx => {
          tx.executeSql(statement, params, (transaction, results) => {
            resolve(results);
          }, (transaction, error) => {
            reject(error);
          });
        });
    });

Solution

  • Create a new observable, as you do with a promise, and then call observable.next(<var>) to pipe the result to the subscribed object. Ensure you also call observable.complete() to notify the observable that the pipe can be closed.

    This code is the rxjs equivalent to the above code:

    import { Observable } from 'rxjs';
    
    const observable = new Observable(observer => {
        this.websqlDatabase.transaction(tx => {
            tx.executeSql(statement, params, (transaction, results) => {
                observable.next(results);
                observer.complete();
            }, (transaction, error) => {
                observable.error(error);
            });
         });
    });
    
    observable.subscribe(value => console.log(value));