【问题标题】:How to change the subscription of an Observable in response to user action?如何更改订阅 Observable 以响应用户操作?
【发布时间】:2017-01-25 23:07:33
【问题描述】:

我正在向我的应用程序添加地理定位,我需要在用户实际请求位置之前的某个时间启动 observable Geolocation.watchPostion()

我有创建实例变量的想法

private locationObserver = (stub observer);
private locationSubscription;

然后做

this.locationSubscription = Geolocation.watchPosition().subscribe(
  next => this.locationObserver.next(next),
  err  => this.locationObserver.error(error),
  comp => this.locationObserver.complete(complete)
)

然后在稍后调用以下命令。

onRequestLocation(){
  this.locationObserver = Observer.create(
    location => {
      this.doMyStuff(location);
      this.locationSubscription.unsubscribe();
    }
  )
}

但是,这并不是正确的做法。这很糟糕吗?

我的目标是启动Geolocation.watchPosition(),然后响应用户事件,开始做某事。我还希望在用户事件之后 5 秒发生超时事件。

这是另一种感觉仍然不对的可能性:

我制作实例变量

private userEventHasOccured
private locationSubscription

然后做

this.locationSubscription = Geolocation.watchPosition().subscribe(
  next => {
    if (userEventHasOccured) {
      this.doMyStuff(next);
      this.unsubscribeLocation();
    }
  }
)

public unsubscribeLocation() {
  this.locationSubscription.unsubscribe();
}

onUserEvent(){
  this.userEventHasOccured = true;
}

另外,有没有一种不那么烦人的订阅方式?

【问题讨论】:

    标签: angular ionic-framework ionic2 rxjs


    【解决方案1】:

    我的问题是缺乏理解。当然,一个 observable 可以有多个订阅。

    编辑:对不起!更多解释。

    最后,我的工作解决方案是声明实例变量

    this.stubSubscription
    this.actualSubscription
    

    然后分别在页面加载、用户操作和页面离开时调用以下代码。

    ionViewDidEnter() {
      this.stubSubscription = Geolocation.watchPosition()
        .subscribe(() => {}, () => {});
    
    onUserAction() {
      this.actualSubscription = Geolocation.watchPosition()
        .first(position => position.coords.accuracy <= 50) // 1st accurate-enough result
        .subscribe(position => this.doMyStuff(position))
    
    ionViewWillLeave() {
      this.stubSubscription.unsubscribe();
      this.actualSubscription.unsubscribe();
    }
    

    ionic 似乎非常擅长在用户离开时实际调用willeave。如果没有调用,那么地理定位会一直运行,直到应用程序关闭,这很糟糕。我想以一种更具反应性而不是命令性的方式来做到这一点......

    编辑 2:我确信这仍然不是最好的方法——如果您有任何建议,请告诉我!

    【讨论】:

    • 请详细说明可行的解决方案(代码)。当前的答案并没有真正提供足够的信息。谢谢! :)
    • 当然。我的解决方案最终是在同一个 observable 上创建 两个 订阅——一个用于“启动”它,一个用于响应用户输入——然后取消订阅它们以“停止”observable。
    • 看起来更好!你会为此获得 +1 ;)
    猜你喜欢
    • 2015-05-19
    • 2021-01-11
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多