The Signal, Threading and You

Multithreading can be hard - let’s make it a bit easier by using signals.

So far we’ve seen how to implement your own signal and why transforms are usefull. Now we can take a look at our first real world example: Transforming signals between different threads.

Remember the ensure method from the last post? This method transforms a signal, even if it was not successfull. Let’s define a transform that returns on another thread:

class Thread {
  static func main<T>(a: Result<T>, completion: Result<T>->Void) {

This method just executes a completion handler on the main Thread. It’s pretty basic and simple to use:

let result = Result.Success("Hello")
Thread.main(result) { result in
    // result is now on main thread

But as this function conforms to the signal’s ensure method, we can also use that:

.next { text in
    // use text on main thread

Putting this all together we can do some calculation on the background thread, go back to main and then use the calculated value:

.map { name in
    return "Hello \(name)"
.next { text in

You can find the implementation for Thread.main and Thread.background on the Github Repository. Now we have everything we need to do our first example application in the next post.

Read more posts from this series:
  1. A Swifter Way Of Handling Errors
  2. Transforming The World Into A Better Place
  3. How To Train Your Monad
  4. Sending A Signal To Space
  5. The Signal, Threading and You.
  6. Wrapping View Controllers in Signals