使用过滤器使用MVVM在SwiftUI中重新加载数据

时间:2020-06-09 20:42:04

标签: swift swiftui swiftui-environment

我在SwiftUI的MVVM代码中有此代码。我的目标是应用程序首次加载时返回没有过滤器的结果。当我按下视图上的按钮以触发CatLotViewModel重新加载过滤后的数据,但似乎不知道可以触发它时。

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)
    }
}

1 个答案:

答案 0 :(得分:0)

使用isFiltered作为参数向视图模型添加加载函数。按下按钮时调用该功能。

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)

    }
}