rxjswechat-miniprogram

convert certain type of callback to to observable


I am have an api like this: (This is a wechat-miniprogram api.)

wx.request({
  url: 'test.php', 
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' 
  },
  success (res) {
    console.log(res.data)
  },
  fail(err) {
    console.log(err)
  },
  complete(res) {
    console.log(res.data)
  }
})

However I want to use it like this: (I want to use it like an observable.)

rxwx.request({
  url: 'test.php', 
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' 
  },
}).subscribe(
  (res) => {
    console.log(res.data)
  },
  (err) => {
    console.log(err)
  },
  (res) => {
    console.log(res.data)
  }
)

I cannot transform wx.login with bindCallback or bindNodeCallback. Please help. Thanks in advance :D


Solution

  • Use Observable constructor instead

    const request=new Observable(emitter=>{
    wx.request({
      url: 'test.php', 
      data: {
        x: '',
        y: ''
      },
      header: {
        'content-type': 'application/json' 
      },
      success:emitter.next
      fail:emitter.error
      complete:emitter.complete
    })
    
    return ()=>{ //... clearn up logic here  }
    }