簡體   English   中英

沒有調用RxSwift訂閱塊

[英]RxSwift subscribe block not called

我正在玩RxSwift,我被一個簡單的玩具程序困住了。 我的程序基本上包含一個模型類和一個viewcontroller。 該模型包含一個observable,它在異步網絡調用之后在主隊列上更新,viewcontroller在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丟失了它的觀察者。 有人知道發生了什么或如何調試這個?

最好

如果讀取這個人有興趣。 這是一個重構錯誤,重命名變量后我停止將observable傳遞給ViewController。 相反,我創造了一個新的... facepalm

以下是RxSwift中訂閱的一些有用的片段(日語)

例如,訂閱不同的事件:

let source: Observable<Int> = create { (observer: ObserverOf<Int>) in
    sendNext(observer, 42)
    sendCompleted(observer)
    return AnonymousDisposable {
        print("disposed")
    }
}

let subscription = source.subscribe { (event: Event<Int>) -> Void in
    switch event {
    case .Next(let element):
        print("Next: \(element)")
    case .Completed:
        print("Completed")
    case .Error(let error):
        print("Error: \(error)")
    }
}

Clean and Build為我解決了問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM