如何解决SwiftUI +合并框架+ MVVM Publisher返回空列表
我正在 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()
}
}
}
谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。