Created
August 24, 2017 08:04
-
-
Save nmeylan/ee3f85346aa75907558b8cff9e3ef328 to your computer and use it in GitHub Desktop.
Auto reconnect websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import VueWS from 'vue-native-websocket' | |
import Observer from 'vue-native-websocket/src/Observer' | |
import App from './App' | |
import store from './store' | |
const wsOptions = {store: store, format: 'json'} | |
Vue.use(VueWS, "myWsEndpoint", wsOptions) | |
new Vue({ | |
el: '#app', | |
store, | |
template: '<App/>', | |
components: {App}, | |
created () { | |
this.unsubscribe = this.$store.subscribe((mutation, state) => { | |
if (mutation.type === 'SOCKET_ONCLOSE' || | |
// On error and while not reconnecting (state managed in my store) | |
(mutation.type === 'SOCKET_ONERROR' && !state.websocket.socket.isConnected && !state.websocket.socket.isReconnecting)) { | |
this.reconnectWebSocket() | |
} | |
}) | |
}, | |
methods: { | |
reconnectWebSocket () { | |
setTimeout(() => { | |
this.$store.commit('SOCKET_ONRECONNECTING', this.$socket) | |
this.$socket = new Observer(wsEndpoint, wsOptions) | |
this.$socket.onopen = () => { | |
this.$store.commit('SOCKET_ONOPEN', this.$socket) | |
} | |
}, 2000) | |
} | |
}, | |
beforeDestroy () { | |
this.unsubscribe.call() | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment