0

I have this code in an MVVM code in SwiftUI. My Objective is when the app loads for the first time to return the result without the filter. When I press the button on the view to trigger CatLotViewModel to reload the filtered data but can't seem to figure out I can trigger it.

class CatLotViewModel: ObservableObject {
    //MARK: - Properties
    @Published var catViewModel = [CatViewModel]()

    private var cancellabels = Set<AnyCancellable>()

    init() {
        MyAPIManager().$cat.map{ kitten in
            // Filter
            let filtered = kitten.filter{ ($0.meals.contains(where: {$0.feed == false}))}
            return filtered.map { park in
                MyCatViewModel(parking: park)
            }
//            return kitten.map { park in
//                CatViewModel(parking: park)
//            }
        }
        .assign(to: \.catViewModel, on: self)
        .store(in: &cancellabels)
    }
}
G B
  • 2,323
  • 3
  • 18
  • 32

1 Answers1

0

Add a load function to your view model with isFiltered as a parameter. Call the function when pressing a button.

struct ContentView: View {

    @ObservedObject var catLotViewModel = CatLotViewModel()

    var body: some View {
        Button(action: { self.catLotViewModel.load(isFiltered: true) }) {
            Text("Reload")
        }
    }
}

class CatLotViewModel: ObservableObject {
    //MARK: - Properties
    @Published var catViewModel = [CatViewModel]()

    private var cancellabels = Set<AnyCancellable>()

    init() {
        loadData(isFiltered: false)
    }

    func loadData(isFiltered: Bool) {
        MyAPIManager().$cat.map{ kitten in    
            if isFiltered {
                let filtered = kitten.filter{ ($0.meals.contains(where: {$0.feed == false}))}
                return filtered.map { park in
                    MyCatViewModel(parking: park)
                }
            } else {
                return kitten.map { park in
                    CatViewModel(parking: park)
                }
        }
        .assign(to: \.catViewModel, on: self)
        .store(in: &cancellabels)

    }
}
G B
  • 2,323
  • 3
  • 18
  • 32
Jack Goossen
  • 799
  • 4
  • 14