我正在玩 RxSwift,我被一个简单的玩具程序困住了。我的程序本质上包含一个模型类和一个视图控制器。该模型包含一个在异步网络调用后在主队列上更新的可观察对象,视图控制器在 viewDidLoad() 中订阅。AppDelegate 初始化模型并将其传递给 ViewController 并触发网络请求。
class GalleryModel {
var galleryCount: BehaviorSubject<Int>
init() {
galleryCount = BehaviorSubject.init(value:0)
}
func refresh() {
doAsyncRequestToAmazonWithCompletion { (response) -> AnyObject! in
var counter = 0
//process response
counter = 12
dispatch_async(dispatch_get_main_queue()) {
self.galleryCount.on(.Next(counter))
}
return nil
}
}
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var galleryModel: GalleryModel?
override func viewDidLoad() {
super.viewDidLoad()
galleryModel?.galleryCount.subscribe { e in
if let gc = e.element {
self.label.text = String(gc)
}
}
}
}
class AppDelegate: UIResponder, UIApplicationDelegate {
var galleryModel: GalleryModel?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//do amazon setup
galleryModel = GalleryModel()
if let viewController = window?.rootViewController as? ViewController {
viewController.galleryModel = GalleryModel()
}
return true
}
func applicationDidBecomeActive(application: UIApplication) {
galleryModel?.refresh()
}
标签只更新一个,它显示“0”。我预计标签会更新两次,第一次更新后显示“0”,处理网络请求后第二次更新后显示“12”。dispatch_async 块中的断点被命中,但似乎 galleryCount 失去了它的观察者。有人知道发生了什么或如何调试吗?
最好的