我正在 Swift-UI 中将 MVVM架构与 Combine Framework 和 Alamofire 一起使用。 但是,数据将返回到可观察对象,并且正在打印,这意味着Alamofire和来自api层的已发布数据,但从可观察对象将无法查看。 我在发布者中打印响应及其打印,但不返回查看。
以下是可观察对象。
import SwiftUI
import Combine
class CountryViewModel: ObservableObject {
@Published var countryResponse:[CountryResponse] = []
@Published var isLoggedIn = false
@Published var isLoading = false
@Published var shouldNavigate = false
private var disposables: Set<AnyCancellable> = []
var loginHandler = CountryHandler()
@Published var woofUrl = ""
private var isLoadingPublisher: AnyPublisher<Bool, Never> {
loginHandler.$isLoading
.receive(on: RunLoop.main)
.map { $0 }
.eraseToAnyPublisher()
}
private var isAuthenticatedPublisher: AnyPublisher<[CountryResponse], Never> {
loginHandler.$countryResponse
.receive(on: RunLoop.main)
.map { response in
guard let response = response else {
return []
}
print(response)
return response
}
.eraseToAnyPublisher()
}
init() {
countryResponse = []
isLoadingPublisher
.receive(on: RunLoop.main)
.assign(to: \.isLoading, on: self)
.store(in: &disposables)
isAuthenticatedPublisher.map([CountryResponse].init)
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { [weak self] value in
guard let self = self else { return }
switch value {
case .failure:
self.countryResponse = []
case .finished:
break
}
}, receiveValue: { [weak self] weather in
guard let self = self else { return }
self.countryResponse = weather
})
.store(in: &disposables)
// isAuthenticatedPublisher
// .receive(on: RunLoop.main)
// .assign(to: \.countryResponse, on: self)
// .store(in: &disposables)
}
public func getAllCountries(){
loginHandler.getCountryList()
}
public func getAllUnis(_ id:Int){
loginHandler.getCountryList()
}
}
查看代码
struct ContentViewCollection: View {
@Binding var selectedCountryId:Int
var axis : Axis.Set = .horizontal
var viewModel:CountryViewModel
@State var countries:[CountryResponse] = []
var body: some View {
ScrollView (.horizontal, showsIndicators: false) {
HStack {
ForEach(self.viewModel.countryResponse) { (postData) in
Button(action: {
self.selectedCountryId = postData.countryID ?? 0
}){
WebImage(url: self.imageURL(postData.countryName ?? ""))
.resizable()
.indicator(.activity)
.scaledToFit()
.frame(minWidth: 40,maxWidth: 40, minHeight: 40, maxHeight: 40, alignment: .center)
}
}
}
}.onAppear() {
self.loadData()
}
}
}
谢谢。