我是RxSwift的新手,很容易与Observable的使用混淆。 我想返回一个对象集合作为Observables
在我的项目中,我使用:
这是我的 DataController
这是我做Api电话的地方。
import Foundation
import RxSwift
protocol DataControllerProtocol {
func fetchStatusCode() -> Observable<[StatusCode]>
func fetchStatusCodeImages() -> Observable<[StatusCode]>
}
class DataController {
let client = APIClient.shared
// Private
private let disposeBag = DisposeBag()
public init() {}
}
extension DataController: DataControllerProtocol {
func fetchStatusCode() -> Observable<[StatusCode]> {
return fetchCodes().asObservable()
}
func fetchStatusCodeImages() -> Observable<[StatusCode]> {
return fetchCodesImages().asObservable()
}
}
private extension DataController {
func fetchCodes() -> Observable<[StatusCode]> {
var statusCodes:[StatusCode] = []
client.execute(service: .statusCode) { dicts in
statusCodes = try! dicts.map({ dict -> StatusCode in
let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
let jsonDecoder = JSONDecoder()
let code = try jsonDecoder.decode(StatusCode.self, from: data!)
print("code : \(code)")
return code
})
}
return Observable.just(statusCodes)
}
func fetchCodesImages() -> Observable<[StatusCode]> {
return Observable.empty()
}
}
这是我的 ViewModel - 我初始化我的dataController来获取我的数据
class ViewModel {
// MARK: Private properties
private var privateDataSource: [StatusCode] = []
private let disposeBag = DisposeBag()
// MARK: Outputs
public var dataSource: Observable<[StatusCode]>
init() {
self.dataSource = Observable.just(privateDataSource).asObservable()
}
var data:Variable<[StatusCode]> = Variable([])
let dataController = DataController()
func loadData() -> Observable<[StatusCode]> {
return dataController.fetchStatusCode()
.do(onNext: { codes in
self.privateDataSource = codes
}, onError: { error in
print(error.localizedDescription)
})
}
}
,在我的 ViewController 中 我尝试将结果绑定到tableViewCells 问题是dataSource等于0
**导入UIKit 导入RxSwift 导入RxCocoa class ViewController:UIViewController {
@IBOutlet weak var tableView: UITableView!
private let disposeBag = DisposeBag()
let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
_ = viewModel.loadData()
tableView.delegate = nil
tableView.dataSource = nil
setupTableViewBinding()
}
} 扩展ViewController {
private func setupTableViewBinding() {
viewModel.dataSource
.bind(to: tableView.rx.items(cellIdentifier: "cell",
cellType: UITableViewCell.self)) { row, element, cell in
cell.textLabel?.text = "\(element.title)"
}.disposed(by: disposeBag)
}
} **
这是我的Xcode的截图。代码确实超过了do .do(onNext: 并且,我们可以看到dataSources计数保持为0