Observable properties

Author: Lonewolfwilliams (http://www.lonewolfwilliams.com)

Observable Properties
Sometimes when we need data it isn't available. A common example may be when the data is retrieved asynchronously, that is to say that you request the data, wait an unspecified time and then receive the data, typically in a callback.

Observable properties provide an elegant solution to the kind of problem outlined above, essentially they are an event dispatcher wrapped in the accessor method of a class property, that will allow the observing code to 'know' when a property is updated. As we will see the concept can be taken further to make some pretty funky designs.

Why Observe Properties ?
First a simple example, let us suppose that the player username is retrieved from a webservice, asynchronously by the UserDataModel class:

Usage
Usage is simple:

There are some pretty neat things that you can do with this simple pattern:

You could use a co-routine for a non-blocking subroutine that populates something 'in the background' (although, of course, this isn't actually a thread)

Or you could add observable properties to a datamodel that has some synchronous and some asynchronous data, that way (with some clever design decisions) you don't have to halt execution until the whole model is available, just pause the functionality specific to the asynchronous data.

An Observable List
If you want to make your code more modular, you could make observable versions of types that you use often, for example here is an implementation of an observable list that I use (for those who are wondering why I have written a wrapper class, instead of subclassing, I prefer composition over inheritance as a design choice):