【问题标题】:RXJS 5 bindCallback when the callback is the first argumentRXJS 5 bindCallback 当回调是第一个参数
【发布时间】:2017-05-02 08:32:36
【问题描述】:

我想转换一个函数:

static getCurrentPosition(geo_success, geo_error?, geo_options?)

到一个可观察的。

如您所见,函数的第一个参数是成功回调。

RxJS 5 bindCallback 适用于成功回调是最后一个参数的函数。

有没有办法使用bindCallback on static getCurrentPosition(geo_success, geo_error?, geo_options?)?

如果不是,那么我将手动将函数转换为 Promise,例如数字 2 here

有问题的函数可以找到here

我想将其实现为可观察对象:

navigator.geolocation.getCurrentPosition(
  (position) => {
    updateRegion(position)
    store.dispatch(getCurrentLocation(position))
  },
  error => Observable.of(getCurrentPositionRejected(error)),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
)

我尝试实现以下答案:

    class Vepo extends Component {
      componentDidMount() {
        const { store } = this.context
        this.unsubscribe = store.subscribe(() => { })
        store.dispatch(fetchCategories())
        store.dispatch(getCurrentPosition())

************implementation starts here******************************
        const bound = Observable.bindCallback((options, cb) => {
          if (typeof options === 'function') {
            cb = options
            options = null
          }

          navigator.geolocation.getCurrentPosition(cb, null, options)
        })
       let x = bound(this.getPosition)

        x.subscribe(
        function (x) {
          console.log('Next: %s', x)
        },
        function (err) {
          console.log('Error: %s', err)
        },
        function () {
          console.log('Completed')
        })

       x.onNext()
      }

      getPosition(position) {
        console.log(position)
        return position
      }

console.log() 仅来自内部 getPosition()

【问题讨论】:

    标签: javascript react-native rxjs observable rxjs5


    【解决方案1】:

    使用重新排列的参数创建一个新函数

    const bound = Rx.Observable.bindCallback((options, cb) => {
      if(typeof options === 'function') {
        cb = options
        options = null
      }
    
      navigator.geolocation.getCurrentPosition(cb, null, options)
    })
    

    如果你想处理错误,或者使用bindNodeCallback

    【讨论】:

    • 谢谢。我已经用我的尝试更新了我的问题。你知道如何触发 onNext 吗?它只是来自getPosition() 内部的console.log()ing。
    • @BeniaminoBaggins 不确定我是否正确理解了您的问题。你不应该手动触发onNext。您需要使用正确的选项致电boundconst currentPosition$ = bound() 并订阅 currentPosition$.subscribe(position => console.log(position))
    • Ohhhhh 所以“回调函数”或“成功案例”进入subscribe,而不是const currentPosition$ = bound()
    • 我看到你的例子有一个options 参数。我的选项会进入currentPosition$ = bound({option1: option1Value}) 吗?而回调,进入subscribe?
    • @BeniaminoBaggins Right options 去可观察工厂。 callback 转到subscribe
    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 2019-10-15
    • 2011-10-24
    相关资源
    最近更新 更多