Easy Publishers
Ever wondered how to create a simple publisher?
In this blog i'll try to show you the basics
Firstly we need to import the required frameworks
// Used for the ObservableObject
import Combine
// The easiest for publishers
import SwiftUI
Published object
We're going to create a class what subclasses ObservableObject
and contains a @Published
variable.
(for this example it is also using a timer to update the value)
class MyObject: ObservableObject {
// This published variable will be updated several times.
@Published var y: String
// Set a default value to y, and start the timer
init() {
// Set the value of y to Loading...
y = "Loading..."
// Run this function after 5 seconds on the main thread.
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.upd() // Update
}
}
func upd() {
// Set the value of y to Published World
y = "Published World"
// Tell the system that this ObservableObject class is updated.
self.objectWillChange
}
}
(SwiftUI) View
struct MyView: View {
// Define our object(class) as Observed
@ObservedObject var v = MyObject()
var body: some View {
Text(v.y) // This will change automatically if y is changed
}
}
Full code
import Combine
import SwiftUI
class MyObject: ObservableObject {
@Published var y: String
init() {
y = "Loading..."
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.upd()
}
}
func upd() {
y = "Published World"
self.objectWillChange
}
}
struct MyView: View {
@ObservedObject var v = MyObject()
var body: some View {
Text(v.y)
}
}
Read more
- Implementing Sign in with Apple • 6 minutes reading time.
- Simplifying App Onboarding with OnboardingKit • 5 minutes reading time.
- What is @frozen • 5 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook