I want to store objects in an array in a component every time a subscribed store is updated with data from a WebSocket. My goal is to display the last N
data points I have received (N=1000
for instance).
The store is defined in socket.js
:
import { readable } from 'svelte/store';
export const datastream = readable([], set => {
let socket = new WebSocket("ws://localhost:8765")
let data = [];
socket.onmessage = function (event) {
let { time, value } = JSON.parse(event.data);
// update the data array
// TODO: set a max buffer size
data = [...data, {"time": time, "value": value}];
// set the new data as store value
set(data)
}
})
I have a Chart.svelte
component where a) the last N
points should be plotted (implementation not shown), and b) it should update every time the store subscription callback is triggered. The challenge is that I may need to preprocess the WebSocket data before using it. In Chart.svelte
:
<script>
...
import { datastream } from './socket.js';
export let plot_data;
const unsubscribe = datastream.subscribe(data => {
plot_data = []
for (let datum of data) {
plot_data = [...plot_data, {x: datum.time, y: datum.value}]
}
});
$: {...
some stuff that sets up plotting
...}
</script>
<div class='my-chart'>
...(plot_data)
</div>
My concern is whether this is the most effective approach. It works, but I have a duplicate array in the datastream
store, and I rebuild the plot_data
array completely each time a new value is received.
I tried subscribing to only the most recent data point in the store, but I couldn't find a way to capture the store update and trigger a new entry into the plot_data
array to refresh the plot.