Skip to content

Instantly share code, notes, and snippets.

@theisegeberg
Created March 22, 2020 17:45
Show Gist options
  • Save theisegeberg/edc2a52ba0a186cdbf6f5718b25a0240 to your computer and use it in GitHub Desktop.
Save theisegeberg/edc2a52ba0a186cdbf6f5718b25a0240 to your computer and use it in GitHub Desktop.
MacOS combine swiftui example
import SwiftUI
import Combine
struct Todo:Codable {
let userId:Int
let id:Int
let title:String
let completed:Bool
}
class StaticPublisherMaker {
static func makeNetworkPublisher() -> AnyPublisher<String,Error> {
print("Make publisher")
let url = URL(string:"https://jsonplaceholder.typicode.com/todos/\((1..<5).randomElement()!)")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
URLSession.shared.configuration.urlCache = .none
return URLSession.shared
.dataTaskPublisher(for: request)
.map(\.data)
.decode(type: Todo.self, decoder: JSONDecoder())
.print()
.map(\.title)
.eraseToAnyPublisher()
}
}
class HelperClass:ObservableObject {
@Published var output:String = "not set"
var cancellable:AnyCancellable? = nil
var isOn:Bool = false
init() {
print("Making helper class")
}
deinit {
print("De init")
}
func getBinding() -> Binding<Bool> {
return Binding<Bool>(get: {
print("Getting",self.isOn)
return self.isOn
}, set: {
print("Setting",self.isOn,$0)
self.isOn = $0
})
}
func goDo() {
self.cancellable = StaticPublisherMaker.makeNetworkPublisher().replaceError(with: "error").receive(on: DispatchQueue.main).assign(to: \.output, on: self)
}
}
extension View {
func eraseToAnyView() -> AnyView {
return AnyView(self)
}
}
struct ContentView: View {
@State var showSubView = false
var body: some View {
VStack {
SubView()
Spacer()
}.frame(width: 300, height: 200)
}
}
struct SubView: View {
@ObservedObject var helper = HelperClass()
var body: some View {
VStack {
Button(action: {
self.helper.goDo()
}) {
Text("Fetch!")
}
Text("Output: \(self.helper.output)")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment