Realtime State Application
GState watch API could use for realtime application. It is simple chat sample which use state.watch and socket.io.
var state = new GState();
var counter = Date.now();
io.on("connection", function(socket) {
console.log("client connect");
const watcher = state.watch({
messages: { _: 1 }
},
result => {
console.log(result);
if (result && Array.isArray(result.messages)) {
socket.emit("messages", result.messages.slice(-10));
}
});
socket.on("disconnect", function() {
console.log("client disconnect");
watcher();
});
socket.on("new message", function(msg) {
counter++;
const id = new Date().getTime() + counter % 1e9;
state.set({
messages: {
[id]: msg
}});
});
});