ViewModel 在此调用Api,并将响应存储在watchLaterDataArr变量中
class HomeViewModel: ObservableObject {
@Published var pageCount = ""
@Published var hasNoMoreRows = false
@Published var watchLaterDataArr = [WatchLaterModelResponseData]()
init(apiService: IStudioRepository) {
self.apiService = apiService
}
func getWatchLaterListAPI() {
apiService.getWatchLaterShoSeriesPage(page: self.pageCount)
.receive(on: RunLoop.main)
.sink(receiveCompletion: { [weak self] (completion) in
switch completion {
case .finished:
break
case .failure(let error):
}
}, receiveValue: { response in
self.getStudioLatestReleasesSuccess(response)
})
.store(in: &self.cancellableBag)
}
func getStudioLatestReleasesSuccess(_ result: WatchLaterModel) {
if(result.statusCode == 200) {
for i in 0..<(result.response?.data.count)!{
if !self.hasNoMoreRows {
self.watchLaterDataArr.append((result.response?.data[i])!)
}
}
if result.response?.nextPage != nil && (result.response?.nextPage ?? "") != ""{
self.pageCount = result.response?.nextPage ?? ""
getWatchLaterListAPI()
}
else {
print(self.watchLaterDataArr.count)
self.hasNoMoreRows = true
}
}
}
}
视图即使在视图模型是可观察对象并且使用了发布者变量的情况下,如果不满足或未调用条件,在“视图”中也不反映数据。
struct WatchLaterView: View {
@Environment(\.presentationMode) var presentation
@EnvironmentObject var watchLaterViewModel:HomeViewModel
var body: some View {
VStack {
VStack{
if (self.watchLaterViewModel.watchLaterDataArr.count > 0 && self.watchLaterViewModel.hasNoMoreRows) {
QGrid(self.watchLaterViewModel.watchLaterDataArr, columns: 3) {
StudioWatchLaterCellView(imageUrl: $0.thumbnailImage ?? "",videoItem: $0)
}
}
Spacer()
}
}.onAppear {
self.watchLaterViewModel.getWatchLaterListAPI()
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
称为HomeView的是tabBar之类的
HomeView().environmentObject(HomeViewModel(apiService: Constants.studioApiService))
.tabItem {
Text("Home")
self.isSelected == 0 ? Image("Home_selected") : Image("Home")
} .tag(0)
请帮忙,代码太大了,我不能再缩短它了。