I have a View Model whose datasource can update 1 of 2 ways.
there is a
func fetchData()function that fetches some data async from a server.there is a separate WebSocket class/manager that this ViewModel is using, and it receives data from the websocket when some is sent.
Both of these need to operate on the same datasource var datasource: [MyData]
What's the best way to ensure the datasource is accurate and up to date?
In #1 and #2, should I dispatch whatever results they returned to a separate function, who will dispatch some work to an async serial queue, to ensure there are never 2 queues/threads attempting to operate on my datasource at the same time?
Something like...
func fetchData() {
...
{ [weak self] fetchResult in
self?.updateDataSource(fetchResult)
}
...
}
func websocketDataDidUpdate() {
...
{ [weak self] socketResult
self?.updateDataSource(fetchResult)
}
...
}
let serialQueue = DispatchQueue(label: "com.blah.className.datasourceSerialQueue")
func updateDataSource(data: [MyData]) {
serialQueue.async {
//do data updates in here. Sometimes replace all data, sometimes potentially look for a delta and only replace the delta
}
}
Yes, you should.
Not only to avoid creating garbage data but also multi-treading read write to your data source.
Furthermore, you should avoid mixing up two types of modification amoung your fetching and websocket, it could easily go wrong since you cannot ensure the right receiving sequence of "replacing the delta" tasks from two separate channel.