简体   繁体   中英

Unexpected undefined returned as subscription from Observable, where object expected

I cannot find the issue with the code below, why I am getting undefined for subscription, when an object has been returned that defines the unsubscribe method. Ignore map() as I just call static fromTimeout directly here.

class Observable {
  constructor(subscribe) {
    this._subscribe = subscribe
  }
  // Expose public api method for observers to use...
  subscribe(observer) {
    this._subscribe(observer)
  }

  static fromTimeout(time) {
    return new Observable(function(observer) {
      let handler = function() {
        observer.next("next value")
        observer.complete()
      }
      const timeout = setTimeout(handler, time)

      return {
        unsubscribe: function() {
          clearTimeout(timeout)
        }
      }
    })
  }
  map(projection) {
    const self = this

    return new Observable(function(observer) {
      const subscription = self.subscribe({
        next: function(value) {
          observer.next(projection(value))
        },
        complete: function() {
          observer.complete()
        }
      })

      return subscription
    })
  }
}
const obs1 = Observable.fromTimeout(500)

const subscription = obs1
  // .map(v => v.toUpperCase())
  .subscribe({
    next: function(value) {
      console.log("next: ", value)
    },
    complete: function() {
      console.log("complete called")
    }
  })

setTimeout(function() {
  console.log(subscription) // WHY undefined!?
  subscription.unsubscribe()
}, 1000)

The return statement is missing in:

subscribe(observer) {
    return this._subscribe(observer)
}

 class Observable { constructor(subscribe) { this._subscribe = subscribe } // Expose public api method for observers to use... subscribe(observer) { return this._subscribe(observer) } static fromTimeout(time) { return new Observable(function(observer) { let handler = function() { observer.next("next value") observer.complete() } const timeout = setTimeout(handler, time) return { unsubscribe: function() { clearTimeout(timeout) } } }) } map(projection) { const self = this return new Observable(function(observer) { const subscription = self.subscribe({ next: function(value) { observer.next(projection(value)) }, complete: function() { observer.complete() } }) return subscription }) } } const obs1 = Observable.fromTimeout(500) const subscription = obs1 // .map(v => v.toUpperCase()) .subscribe({ next: function(value) { console.log("next: ", value) }, complete: function() { console.log("complete called") } }) setTimeout(function() { console.log(subscription) // WHY undefined!? subscription.unsubscribe() }, 1000) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM