当回调是第一个参数时,RXJS 5 绑定回调



我想转换一个函数:

static getCurrentPosition(geo_success, geo_error?, geo_options?)

到可观察量。

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

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

有没有办法在static getCurrentPosition(geo_success, geo_error?, geo_options?)

如果没有,那么我将手动将函数转换为类似于此处数字 2 的Promise

有问题的函数可以在这里找到

我想将其实现为可观察量:

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()

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

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

或者,如果要处理错误,请使用bindNodeCallback

最新更新