如何在自定义类中使用RxJS?

时间:2017-07-22 12:26:31

标签: javascript rxjs

我们假设我有以下课程:

class XHRUpload {
    constructor() {
        // Some AJAX code here and listening on progress event,
        // and then pass the progress info out of this class.
    }
}

我还有一个Observable对象:

const observable = Rx.Observable.create((obs) => {
    obs.next(/* progress info here */)
})

但是我应该如何在类中使用这个可观察对象才能在类之外使用它呢?

我现在唯一能做的就是:

const observable = Rx.Observable.create((obs) => {
    new XHRUpload(obs)

    // Then in the class...
    obs.next(/* progress info here */)
})

// And then...
observable.subscribe({
    next: value => {/* Progress data... */},
    error: err => {/* Something bad has happened! */},
    complete: () => {/* Transfer has been completed! */}
})

但这似乎是一种不好的做法,不是吗?

1 个答案:

答案 0 :(得分:0)

最后我想出来了!

const observable = new Rx.Subject()

observable.subscribe({
    next: value => {/* Progress data... */},
    error: err => {/* Something bad has happened! */},
    complete: () => {/* Transfer has been completed! */}
})

const obj = new XHRUpload(observable)

课程将是:

class XHRUpload {
    constructor(observable) {
        // Some great code here...

        observable.next(/* some progress data */)
    }
}