I have this "purple warning" on line 31, however my code only works without .receive(on: DispatchQueue.main)
If I set .receive(on: DispatchQueue.main) or .receive(on: RunLoop.main), or simply run on DispatchQueue.main.async {}
the publisher never fires.
Any clues? Is it ok to keep it "purple" ?
class ImageLoader: ObservableObject {
private var cancellable: AnyCancellable?
private var cache: ImageCache
@Published var image: UIImage?
private let url: URL
init(url: URL, cache: ImageCache) {
self.url = url
self.cache = cache
}
deinit {
cancellable?.cancel()
}
func load() {
if let image = cache[url] {
dispatchToMainThreadIfNeeded {
self.image = image
}
return
}
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { UIImage(data: $0.data) }
.handleEvents(receiveOutput: { [weak self] in self?.cache($0) })
.replaceError(with: nil)
.sink { value in
self.image = value // Dispatch on main thread is not firing the publisher..
}
}
func cancel() {
cancellable?.cancel()
}
private func cache(_ image: UIImage?) {
image.map { cache[url] = $0 }
}
}
UDP
what sort of work is .assign(to: \.image, on: self) instead of .sink { self.image = $0 }. Seems like only on device, not on Simulator..