DEV Community

Discussion on: Getting started with SwiftUI and Combine.

Collapse
 
codger profile image
codger

Same as your sample except TodoListViewModel: changed didChange to willChange per Version 4 beta requirements

import Foundation
import SwiftUI
import Combine

public class TodoListViewModel: BindableObject {
public let willChange = PassthroughSubject()

var todos: Todos = [Todo]() {
    willSet {
        willChange.send(self)
    }
}

func shuffle() {
    self.todos = self.todos.shuffled()
}

func sort() {
    self.todos = self.todos.sorted(by: { ($0.pinned ?? false) && (!($1.pinned ?? false)) })
}

func markDone(id: Int) {
    self.todos.first(where: { $0.id == id })?.completed.toggle()
    self.willChange.send(self)
}

func pin(id: Int) {
    self.todos.first(where: { $0.id == id })?.pinned?.toggle()
    self.sort()
}

func load() {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/") else { return }
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        do {
            guard let data = data else { return }
            let todos = try JSONDecoder().decode(Todos.self, from: data)
            DispatchQueue.main.async {
                self.todos = todos
            }
        } catch {
            print("Failed To decode: ", error)
        }
    }.resume()
}

}

Thread Thread
 
kevinmaarek profile image
Maarek

Replacing didChange to willChange did not raise any error, but I noticed you did not added the satisfying types for output and failures. In my case :

public let willChange = PassthroughSubject<TodoViewModel, Never>()

I have no idea of how you could get that kind of error, but check if that's what you missed.