在taro开发的微信小程序中,当切换应用时,网络会被中断后,这个模块可以自动重连

中断重连

对http请求进行封装

//原代码:
async function request() {
await asyncFn(data);
}

//改造后代码:
import {interruptedThenReconnectHttpReq} from '@/dlf/taro/interruptedThenReconnect'
interruptedThenReconnectHttpReq(request)
async function request() {
await interruptedThenReconnectHttpReq(asyncFn)(data);
}

对websocket请求进行改造

//原代码:
Taro.connectSocket().then((task)=>{
task().onOpen(function () {
task().send()
})
task().onError(function (e) {
})
task().onClose(function (e) {
})
task().onMessage(function (data) {
})
})
//改造后代码:
import {interruptedThenReconnectWebSocket} from '@/dlf/taro/interruptedThenReconnect'
const { connectSocket, getCurrentTask } = interruptedThenReconnectWebSocket()
connectSocket().then(()=>{
getCurrentTask().onOpen(function () {
getCurrentTask().send()
})
getCurrentTask().onError(function (e) {
})
getCurrentTask().onClose(function (e) {
})
getCurrentTask().onMessage(function (data) {
})
})

监听返回到应用中,启动重连任务

import {runTask} from '@/dlf/taro/interruptedThenReconnect'
onShow(()=>{ // onShow 为taro的生命周期函数
runTask() // 执行重连任务

})

Functions

interruptedThenReconnectHttpReq
interruptedThenReconnectWebSocket
runTask