Hello. Does anyone have an example of using KVisi...
# kvision
a
Hello. Does anyone have an example of using KVision Chart with dynamic data? More specifically with data from a KVision back-end server? I have a use case where charts need to display data dynamically both using filtering components on the front end as well as refreshing with newly updated data from the back end. I've tried using ObservableList for both the DataSet (and underlying
data
) as well as Labels, but, while the Cart paints properly the first time it seems indifferent to updates of the ObservableLists.
r
Chart
component doesn't support automatic updates, even when used with
ObservableList
. But it's very easy to make it work, just use
subscribe
manually.
Copy code
val datasets = observableListOf(
            DataSets(
                label = "My Second dataset",
                data = listOf(10, 30, 50, 20, 25, 44, -10),
                fill = false
            ),
            DataSets(
                label = "My First dataset",
                data = listOf(100, 33, 22, 19, 11, 49, 30),
                fill = false
            )
        )

        root("kvapp") {
            margin = 20.px
            div {
                width = 600.px
                height = 400.px
                chart(
                    Configuration(
                        ChartType.LINE,
                        labels = listOf("January", "February", "March", "April", "May", "June", "July"),
                        dataSets = datasets
                    )
                ).apply {
                    datasets.subscribe {
                        this.configuration = this.configuration.copy(dataSets = it)
                    }
                }
            }
            button("Generate random data").onClick {
                val newDatasets = datasets.map {
                    it.copy(data = it.data?.map { Random.nextInt(100) })
                }
                datasets.syncWithList(newDatasets)
            }
        }
a
@Robert Jaros Thank you! I made a slight change to your code above - I needed to also control the Labels. So I used an
ObservableValue
and placed the entire Chart
Configuration
object in there. A similar modification to the
datasets.subscribe {...
block above update the Chart config with data updates. That worked