'Is there a way in SwiftUI to transport and handle data from an property to the class?
I have two classes here. Music
which is used to store music url and load metadata, and MusicManager
which is used to store a list of music and sort them after loading of all music's metadata finished.
Since the loading of metadata for each music let metadata = try? await asset.load(.commonMetadata)
is asynchronous, I can't directly call sort function in init()
.
I tried to find some solution using Publisher
in Combine framework that when the metadata is loaded, the publisher will emit a completion, and if MusicManager
received enough completion (same as music list's count), it will perform the sort.
class Music: ObservableObject, Identifiable {
static let publisher = PassthroughSubject<Void,Error>
......
}
class MusicManager: ObservableObject {
......
static var count = 0
let subscriber = Music.pub.sink { completion in
switch completion {
case .finished:
count += 1
if musicList.count == count {
......
}
case .failure(_):
}
} receiveValue: { _ in }
......
}
But it said Instance member 'library' cannot be used on type 'MusicListManager'; did you mean to use a value of this type instead?
How can I am informed, when all music's metadata are already loaded. I would appreciate it if you can give me some advice.
Solution 1:[1]
We don't normally use sink
with ObservableObject
, instead we assign
the end of the Combine pipeline to an @Published
which also makes the lifetime of the pipeline the same as the object's, so there is no need to store cancellables.
However, you mentioned you are using async/await. If using that you don't need ObservableObject
anymore. Just pass the asset into your View
as a let param, and then use the task
modifier to call your async/await code and set an @State
with the result which will cause body
to be called. SwiftUI will calculate the View
hierarchy diff and update the UIKit/AppKit views on screen with the changes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |