Combine - Creating your own Publisher with @Published

You can create your own publisher by implementing the Publisher protocol, but there are more convenient ways of creating your own publisher.

In this article, we will be exploring one of them, but before that, if you haven’t read Combine Framework Beginner Tutorial in Swift, Click Here. And to read Combine - Processing Values with Operators in Swift, Click Here.

WWDC2020 is tomorrow, and we all are excited, If you haven’t subscribed yet, then subscribe now, as I’ll be coming up with the articles of all the latest stuff you’ll see in WWDC.

Now let’s start with my favourite and the easiest way of creating our own publisher, which is @Published annotation. We just need to add this annotation to a property, and the property will act as a publisher.

@Published var wheels : Int

This is how you make a property act like a publisher.

The most important thing to note here is @Published annotation can only be used in a class, we cannot do this with a struct, which is quite dissatisfying.

Let’s look into a proper demonstration of @Published.

class Vehicle {
    @Published var wheels : Int
    
    init(wheels: Int) {
        self.wheels = wheels
        
        // Publishing values with delay
        for i in 2...6 {
            DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + Double(i)) {
                self.wheels = i
            }
        }
    }
}

let vehicle = Vehicle(wheels: 1)

let cancellable = vehicle.$wheels // Accessing publisher with $ operator.
    .sink { wheels in
        print("Number of wheels: \(wheels)")
}

/*
 Output:
 Number of wheels: 1
 Number of wheels: 2
 Number of wheels: 3
 Number of wheels: 4
 Number of wheels: 5
 Number of wheels: 6
 */
 

If you look at the initializer, we are setting new values to our wheels with a delay, and accordingly, in the output shown above, the value is getting printed.

Note: You need to access the publisher with the $ operator, e.g. vehicle.$wheels.

This is how you can create your own publisher with classes. There are two more ways I’ll be covering, so subscribe if you haven’t and receive the latest updates about my upcoming articles.

If you have any suggestions or questions, Feel free to connect me on Twitter or Reddit. 😉

To read, Combine - Creating your own Publisher with PassthroughSubject and CurrentValueSubject, Click Here.

Combine - Creating your own Publishers with PassthroughSubject and CurrentValueSubject

Combine - Processing Values with Operators in Swift