I’m working on a project where I need to listen to any changes in an array of objects. By changes I refer:
- Add/Remove element in the array
- Any change in the existing array elements
Here is the sample code,
enum DownloadState {
case queued
case completed
}
class DownloadTask: ObservableObject {
var downloadState: DownloadState = .queued
}
class DownloadManager {
var downloadTasks = [DownloadTask]()
}
In the above code, DownloadManager
contains an array of DownloadTask
. I want to listen to the changes when,
- A new
DownloadTask
instance is added intodownloadTasks
array - An existing
DownloadTask
instance is removed fromdownloadTasks
array - The underlying
DownloadState
is changed for a particularDownloadTask
indownloadTasks
array
2
Answers
The approach that worked for us:
1. Create a protocol to listen to any changes in the
DownloadTask
2. Passed the
delegate
instance to theDownloadManager
during initialization.3. Called the
delegate
methoddidUpdateDownloadState
whenever thedownloadState
of aDownloadTask
is updated.Example:
A possible approach is to make task a value type and manager as
ObservableObject
with published property for array of tasks, likeSo requested changes can be observed either via
@ObservedObject
wrapper in SwiftUI view or viamanager.$downloadTasks
publisher in any other place.