Conquering ReactiveSwift: Property (Part 5)

Susmita Horrow
Fueled Engineering
Published in
3 min readMar 20, 2018

Welcome to Part 5 of Conquering ReactiveSwift series. In the previous article, we learned how to create, start and observe a SignalProducer. In this article, we will discuss the notion of Property and MutableProperty.

Definition

Property

A Property is an observable container which emits its value whenever its value is changed. It conforms to PropertyProtocol which itself has the following properties:

  • value: Represents the current value
  • producer: A SignalProducer which sends the current value followed by the subsequent changes. This completes when the Property deinitializes or has no further change.
  • signal: A Signal which sends the subsequent changes, not the current value. This completes when the Property deinitializes or has no further change.

How is it useful?

This is quite useful when we just have to deal with values, not errors.

Let’s consider the example from last article.

Print a message of time elapsed on every five seconds interval for fifty seconds.

For this we had created a SignalProducer as follows:

Note that here we have the error of type NoError which means we are not dealing with errors here. This is a good use case when we can wrap this in a Property.

So let’s define a Property.

Here, the initial value of the property is ‘0’ and subsequent values are returned by the signalProducer.

As mentioned earlier, a Property has the properties signal and producer, both of which can be observed, but with a key difference being that a signal does not emit the current value, only subsequent changes to that value.

Observing signal of a property

In this example, we have created a property which takes values from a SignalProducer. We can also create a property which can take values from a Signal as well.

MutableProperty

A MutableProperty is an observable container which emits a value on change just like a Property, but can also be directly mutated. Like Property, it also conforms to thePropertyProtocol.

A MutableProperty can be initialized with an initial value like this:

We can then update its current value as follows:

The signal and producer of a MutableProperty can be observed just like a Property.

MutableProperty is useful when we do Bindings. The MutableProperty then allows us to write code like this:

Here, it means that the value of the mutableProperty is dictated by the signalProducer. We will discuss more about bindings in subsequent articles.

Conclusion

I hope this article gave you an idea of Property and MutableProperty. You can find the sample code here. In the next article, we will introduce the Action, which allows you to better control and execute the behavior of a Signal.

--

--