我能否混合使用async/await Promise和observable RXJS呢?

6

我是一名IT技术人员,正在使用Ionic/Angular和RxJS Observables。

我正试图使用RxJS Observables重构我的代码,以下是我的代码:

ionViewWillEnter() {
    if (this.platform.is('core') || this.platform.is('mobileweb')) {
      this.lat = 37.3675506;
      this.lng = -6.0452695;
      this.printMap();
    } else {
      if (this.platform.is('android')) {       
        this.tryGeolocation();            
      } else if (this.platform.is('ios')) {
        console.log("IOS")
      }
    }
  }

如果用户从Android手机访问,则应检查:isLocationAuthorized,isLocationEnabled()以使用getCurrentPosition()获取当前位置,然后我必须打印Map,其中使用Observables forkjoin。
问题在于检查方法返回承诺,我不知道如何链接此流程。
tryGeolocation是下一个:
 async tryGeolocation() {
    try {
      if (await this.diagnostic.isLocationAuthorized()) {
        if (await this.diagnostic.isLocationEnabled()) {
          this.loading = this.loadingCtrl.create({
            content: 'Localizando...',
            dismissOnPageChange: true
          });
          this.loading.present();
          const {coords} = await this.geolocation.getCurrentPosition();
          this.lat = coords.latitude;
          this.lng = coords.longitude;
          this.loading.dismiss();
          alert(this.lat);
          alert(this.lng);
          this.printMap();
        } else {
         console.log("error1")
        }
      } else {
console.log("error2")
      }
    } catch (e) {
      console.log('Error getting location', e);
    }
  }


printMap() {
    let obs1 = this._sp.getLocationsByPosition(this.lat, this.lng);
    let obs2 = this._sp.getUserFavoriteLocations2();
    this.subscription = forkJoin([obs1, obs2]).subscribe(results => {
      this.allLocations = results[0];
      this.myLocations = results[1];
      this.allLocations = this.allLocations.filter(item => !this.myLocations.some(other => item.id.sid_location === other.id.sid_location && item.id.bid_environment === other.id.bid_environment));   

      this.map = new google.maps.Map(this.mapElement.nativeElement, {
        zoom: 13,
        center: {lat: parseFloat(this.lat), lng: parseFloat(this.lng)},
        zoomControl: true,
        draggable: true            
      });

      new google.maps.Marker({
        position: {lat: parseFloat(this.lat), lng: parseFloat(this.lng)},
        map: this.map,
        icon: {
          url: "https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi2_hdpi.png"
        }
      });
      this.printMarkers();
    });
  }

我尝试将promise转换为可观察对象,像这样:
let obs1 = Observable.fromPromise(this.diagnostic.isLocationAuthorized());
    let obs2 = Observable.fromPromise(this.diagnostic.isLocationEnabled());
    let obs3 = Observable.fromPromise(this.geolocation.getCurrentPosition());

    obs1.flatMap(() => obs2)
      .flatMap(() => obs3)
      .subscribe(coords => {
        console.log(coords);
//CALL TO printMap?
      })

有人能帮我实现这个流程并重构我的代码吗?

提前感谢你。


你能使用 Promise.all() 吗?https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all - Alex K
你能否将这个示例简化为可重现的内容?https://stackoverflow.com/help/mcve - martin
@AlexK 我不这么认为,因为正如您在 tryGeoLocation 上看到的那样,一个依赖于另一个。 - SDLUJO
2个回答

0
你可以使用 fromcombineLatest 将你的 promise 链转换为 RxJS。我在这里发布了一个 stackblitz 示例 - https://stackblitz.com/edit/rxjs-jnrj37?devtoolsheight=60 基本上像这样:
import { combineLatest, from, of } from "rxjs";
import { map } from "rxjs/operators";

const promiseMaker = timeInMS =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("promise done");
      resolve("foo");
    }, timeInMS);
  });

const promise1$ = from(promiseMaker(300));

const promise2$ = from(promiseMaker(500));

const promise3$ = from(promiseMaker(800));

combineLatest(promise1$, promise2$, promise3$).subscribe(() =>
  console.log("Ready!!!")
);

如果承诺彼此依赖,那么您可以使用switchMapmergeMap代替combineLatest,并根据需要链接它们。

0

Rxjs可观察对象和PromisesDefer文档

话虽如此,fromPromise已被弃用,在文档中不再出现。使用from从promise获取可观察对象

import { from } from 'rxjs';

let obs1 = from(this.diagnostic.isLocationAuthorized());
let obs2 = fromPromise(this.diagnostic.isLocationEnabled());
let obs3 = fromPromise(this.geolocation.getCurrentPosition());

但是请考虑它是否适用于您的用例。这个答案会帮助您做出决定

事实证明,您可以将async-await与observables混合使用,但这并不意味着它适用于您的用例。(请谨慎使用此代码

import { defer } from 'rxjs';
defer(async function() {
  const a = await promiseDelay(1000).then(() => 1);
  const b = a + await promiseDelay(1000).then(() => 2);
  return a + b + await promiseDelay(1000).then(() => 3);
})
.subscribe(x => console.log(x)) // logs 7

2
你写到“异步等待和可观察对象不能一起使用”,而你链接的页面却说“从一开始,RxJS 就与 Promises 有很高的互操作性”,并详细解释了它们如何能够很好地共同运作... - hugo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接