Skip to content

Instantly share code, notes, and snippets.

@SlappyAUS
Created February 8, 2021 08:04
Show Gist options
  • Save SlappyAUS/5b4b0ec81c2316d53481b01c352bee33 to your computer and use it in GitHub Desktop.
Save SlappyAUS/5b4b0ec81c2316d53481b01c352bee33 to your computer and use it in GitHub Desktop.
swiftui url update #swiftui #data #url
import Combine
class MyObserableObject: ObservableObject {
@Published var myData: [Int] = []
private var subscription: AnyCancellable?
init() {
subscription = Timer
.TimerPublisher(interval: 1, runLoop: RunLoop.main, mode: .default)
.map { _ -> AnyPublisher<[Int], Never> in
URLSession
.shared
.dataTaskPublisher(for: URL(string: "somefakeurl.com")!)
.map(\.data)
.decode(type: [Int].self, decoder: JSONDecoder())
.replaceError(with: [])
.eraseToAnyPublisher()
}
.switchToLatest()
.receive(on: RunLoop.main)
.assign(to: \.myData, on: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment