Git Product home page Git Product logo

rxwx's Introduction

RxWX

Write less, do more elegantly!

封装了RxJS对象微信小程序API,让你写出更优雅更简介的代码。

RxWX模块支持所有微信小程序中wx对象的属性和函数,例如getUserInfo等。 RxWX模块的Rx属性为RxJS对象,支持RxJS对象所有属性,例如Observable等。

快速起步

直接下载种子项目RxWX-seed解压即可开始编写小程序代码。

安装

  1. 下载

使用github

git clone https://github.com/yalishizhude/RxWX.git

使用npm

npm i rxjs-wx

使用yarn

yarn add rxjs-wx

  1. 拷贝根目录下的Rx.js和RxWX.js到项目目录

  2. 引用文件

import rxwx from 'RxWX.js'

小程序中使用示例

源码地址

同步函数

// 原写法
try {
  let result = wx.removeStorageSync('xx')
  console.log(result) 
} catch(e) {
  console.error('小程序API发现错误')
}

// 使用RxWX,rxwx对象具有wx对象的所有函数和属性,函数返回Observable对象
import rxwx from '../../utils/RxWX.js'

rxwx.removeStorageSync('xx')
  .catch((e) => console.error('RxWX发现错误'))
  .subscribe((resp) => console.log(resp))

异步函数

// 原写法
wx.removeStorage({
  key: 'xx',
  success: function(res) {
    console.log(res)
  },
  error: function(e) {
    console.error('小程序API发现错误')
  }
})
// 引用RxWX,rxwx对象函数参数与wx同名函数一致
import rxwx from '../../utils/RxWX.js'

rxwx.removeStorage({key: 'xx'})
  .catch((e) => console.error('RxWX发现错误'))
  .subscribe((resp) => console.log(resp))

异步嵌套

// 调用小程序原生API
wx.login({
  success(res) {
    wx.getUserInfo({
      success(res) {
        console.log(res.userInfo)
      },
      fail(e) {
        console.error(e)
      }
    })
  },
  fail(e) {
    console.error(e)
  }
})

// 调用RxWX
import rxwx from '../../utils/RxWX.js'

rxwx.login()
  .switchMap(() => rxwx.getUserInfo())
  .catch(e => console.error(e))
  .subscribe(res => console.log(res.userInfo))

异步合并

// 调用小程序API
let getUser =  new Promise((success, fail) => {
  wx.getUserInfo({
    success,
    fail
  })
})
let getSystem =  new Promise((success, fail) => {
  wx.getSystemInfo({
    success,
    fail
  })
})
Promise.all([getUser, getSystem])
.then((resp) => console.log(resp), e => console.error(e))

// 调用RxWX中的Rx对象,包含RxJS所有操作符和函数
import rxwx, {Rx} from '../../utils/RxWX.js'
// 使用zip操作符
Rx.Observable.zip(rxwx.getUserInfo(), rxwx.getSystemInfo())
  .catch(e => console.error(e))
  .subscribe(resp => console.log(resp))

网络请求

http请求

let handlerA = (res) => console.log('handler a:', res)
let handlerB = (res) => console.log('handler b:', res)
// 调用小程序API
let url = 'http://localhost:3456'
wx.request({
  url,
  success(res) {
    // 逻辑与请求的紧耦合
    handlerA(res)
    handlerB(res)
  }
})

// 调用RxWX
let req = rxwx.request({
  url
})
// 轻轻松松将业务逻辑与请求分离
req.subscribe(handlerA)
req.subscribe(handlerB)

websocket

let url = 'ws://localhost:34567'
// 调用微信小程序API
let ws = wx.connectSocket({
  url
})
ws.onOpen(() => {
  ws.send({ data: new Date })
  ws.onMessage(msg => console.log(msg.data))
  ws.close()
  ws.onClose(msg => console.log('Websocket closed.'))
})
// 调用RxWX
rxwx.connectSocket({
  url
})
.subscribe(ws => {
  ws.onOpen(() => {
    ws.send({ data: new Date })
    ws.onMessage(msg => console.log(msg.data))
    ws.close()
    ws.onClose(msg => console.log('Websocket closed.'))
  })
})

事件绑定

import rxwx from '../../utils/RxWX.js'
// 页面对象
let page ={
  data: {
    // 页面数据...
  },
  onLoad: function () {
    // 页面初始化
  },
}
// 使用fromEvent绑定事件,返回Observable对象
rxwx.fromEvent(page, 'bindViewTap')
  .debounceTime(1000)  // 防抖
  .switchMap(() => rxwx.navigateTo({
    url: '../logs/logs'
  }))  // 页面跳转
  .subscribe()
// 初始化页面逻辑
Page(page)

wepy中使用示例

源码地址

  1. 安装RxWX

npm i -S rxjs-wx

当然我更推荐你使用yarn

yarn add rxjs-wx

  1. 引入模块

import rxwx from 'rxjs-wx'

  1. 使用rxwx

src/app.wpy

app.wpy文件

src/pages/index.wpy

index.wpy文件

更多

RxJS

微信小程序API

更多内容请关注公众号“web学习社”。

web学习社


我的新书《了不起的JavaScript工程师:从前端到全端高级进阶》已经在京东上架,旨在帮助初级和中级web前端工程师提升进阶,成为具有全局视野的全能型人才,欢迎选购~

rxwx's People

Contributors

yalishizhude avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rxwx's Issues

typescript 版本

请求有 typescript 的版本吗?虽然 ts 也能调用 js,但少了编译时的类型检查。

When I click on the jump, I will report the error.

formSubmit:()=>{
rxwx.navigateTo({url: '../setTask/setTask'})
.debounce(1000)
.subscribe()
}
error:Rx.js:8064 Uncaught (in promise) TypeError: this.durationSelector.call is not a function
at DebounceSubscriber._next (Rx.js:8064)
at DebounceSubscriber.Subscriber.next (Rx.js:631)
at RxWX.js? [sm]:14
at

Error: no Promise impl found

Promise 貌似没有兼容

const source = Rx.Observable.create(observer => {
        observer.next('foo');

        setTimeout(function() {
          observer.next('bar');
        }, 1000);
      })

      const source1 = source.map(val => `hello ${val}`);

      const subscription = source1.subscribe(value => console.log(value));

      subscription.next('foo1');

      const promise = source1.forEach(value => {
        console.log(value);
      });

      promise.then(()=>console.log('complete'), (err)=>console.log(err));

不维护了吗?

除了封装wx的api,能不能直接使用rxjs?不是封装的,就是这个库在小程序上用

what if request.abort

Hi @yalishizhude,
What if we want to call the Observable.cancel just like calling wx.request.abort?
I am curious about how we can match and connect these 2 things?

Thanks!

如何使用operators ,例如 如何import take pipe catchError 等 操作符

// api.js
import HttpUtil from './httputil'
import {Rx} from 'rxjs-wx'

module.exports = {
  rank(param={}) {
   // return: Observable<Array>, take(10) doesn't work,it's still 100 elements 
    return HttpUtil.get("/api/v2/rank/total/2019/02/14/", param).take(10)
  }
}
// app.js
import Api from './utils/api'
import rxwx, {Rx} from 'rxjs-wx'

App({
  onLaunch: function () {
    Api
    .rank()
    .catch(e => console.log(e)) // when error occur , e is undefined 
    .subscribe(res => console.log(res))
  },
  globalData: {
  }
})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.