HBu*_*HBu 5 ios swift rx-swift
我正在玩 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()
}
Run Code Online (Sandbox Code Playgroud)
标签仅更新一次,显示“0”。我预计标签会更新两次,第一次更新后显示“0”,处理网络请求后第二次更新后显示“12”。dispatch_async 块中的断点被击中,但 galleryCount 似乎失去了其观察者。有人知道发生了什么或如何调试吗?
最好的
| 归档时间: |
|
| 查看次数: |
4992 次 |
| 最近记录: |