RxSwift Subscription Block Not Named

I play with RxSwift and I am stuck in a simple toy program. My program essentially contains a model class and a viewcontroller. The model contains an observable, which is updated in the main queue after an asynchronous network call, the view manager subscribes to viewDidLoad (). AppDelegate initializes the model and passes it to the ViewController and launches a network request.

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()
    }

Only one label is updated, it shows "0". I expected the shortcut to be updated twice, showing "0" after the first update and showing "12" after the second update after processing the network request. The breakpoint in the dispatch_async block hits, but it looks like galleryCount has lost its observer. Does anyone know what is happening or how to debug this?

+4
3

, , - . , ViewController. ... facepalm

+3

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)")
    }
}
0

Cleanliness and assembly solved problems for me

0
source

Source: https://habr.com/ru/post/1609330/


All Articles