DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

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) } }

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay