Getting into combine

Every semester I do a deep dive into something for me complex. This time, I dived into Combine. So, now the first period of this semester is done I thought it was time to write about what I’ve learned.

So, what is Combine

Combine is a reactive programming framework which allows you to process values over time. So as an example, you can do a network request, get the value and process the value and push it to the view in a functional way all using Combine. Using combine, your code can be reduced significant while still maintain readable. Combine is also integrated with the Foundation framework, this helps when using core api functions like notifications.

Okay, so how to use it?

So, for example. When I want to do a network request to https://play.cmdlwd.nl/api/posts to get the latest posts of the Play.CMD website, I have to do the following:

  • Create a Post model that conforms to Decodable
  • Create a URL Session
  • Map the data for decoding
  • Decode data to models
  • Profit 🚀

Okay, so now we know what to do, lets start with creating the right model

struct User: Codable {
    let name: String
    let email: String
}
 
struct Post: Codable {
    let type_of: String
    let id: Int
    let title: String
    let slug: String
    let created_at: String
    let user: User
}

As you can see I created a Post and User model, both implementing Codable. This helps when decoding JSON data using JSONDecoder().

Now that I have the right model to decode, It’s time to make an api request and decode the data.

let data = URLSession.shared.dataTaskPublisher(for: URL(string: "https://play.cmdlwd.nl/api/posts")!)
    .map { $0.data }
    .decode(type: [Post].self, decoder: JSONDecoder())
    .sink(receiveCompletion: { completion in
        print(completion)
    }, receiveValue: { posts in
        posts.forEach { post in
            print(post.title)
        }
    })

The above code does a Network request, decodes the mapped data and logs the posts title for each given post.

As you can see, it’s that simple to do an easy network request. Last semester I tried using Elixir, a functional programming language and with that knowledge. It’s much easier to understand how the data flow works in the publisher when you understand functional programming.

Concluding.

So, now I kinda understand how Combine works. It’s time to get my hands dirty and use it in a real app. I do know that async/await is around the corner. But with the backwards ability of that, right now it’s better to use Combine. So next up is using Combine in my hobby project, Urenmanagement. So I can understand it even better.