Skip to content

Instantly share code, notes, and snippets.

@emin-grbo
Last active May 22, 2022 06:45
Show Gist options
  • Save emin-grbo/6cbe7eb41d2b6ab984cc41b1a0adecf4 to your computer and use it in GitHub Desktop.
Save emin-grbo/6cbe7eb41d2b6ab984cc41b1a0adecf4 to your computer and use it in GitHub Desktop.
Voodo Arch Template
@main
struct mainApp: App {
init() {
// custom init if needed. Analytics setup and similar
}
var body: some Scene {
WindowGroup {
MainView(mainObservableObject: MainObservableObject())
}
}
}
struct MainView: View {
// Good resource in regards to all different propertyObservers used
// https://www.hackingwithswift.com/books/ios-swiftui/sharing-swiftui-state-with-stateobject
// https://www.hackingwithswift.com/quick-start/swiftui/all-swiftui-property-wrappers-explained-and-compared
@StateObject var mainObservableObject: MainObservableObject
var body: some View {
DetailView(observable: mainObservableObject)
}
}
struct DetailView: View {
@ObservedObject var observable: MainObservableObject
var body: some View {
Text(observable.updatableText)
}
.onAppear {
observable.fetchNetworkData()
}
}
@MainActor
class MainObservableObject: ObservableObject {
// Data object which is usually a network manager
private var mainDataObject: MainDataObject = MainDataObject.shared
// All published properties we want to OBSERVE from views that hold a reference to this mainObservableObject
@Published var updatableText = "Hi There!"
func fetchNetworkData() {
Task {
let networkData = mainDataObject.getData
updatableText = networkData.title // here text gets updated and automatically gets refreshed in a view
}
}
}
class MainDataObject {
static let shared = MainDataObject()
func getData() async -> Data? {
// some dummy code as it really depends on what kind of data is fetched and from where
let response = try? await NETWORKCALL
return response?.data
}
}
This example uses https://swiftuivoodo.com/ approach for SwiftUI Architecture and this is one concrete implementation of it.
There are multiple ways to assemble this architecture, which is the main and the most beautiful thing about it.
Currently I adapted it to fit my own needs, but feel free to mold it to the shape that first you best.
I avoided viewModel naming as it confuses the hell out of me as we already have Observable object in SwiftUI
which is essentially a viewModel 😅
Feel free to reach out for any ideas or comments via twitter.com/emin_ui
p.s.
I am using the numbers in file names becuase I want to present files in a specific order,
otherwise git would have placed this explanation half-way
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment