RxSwift minimal Observable.create example

You may use RxExamples for better understanding RxSwift. I found it in RxSwift repo. It helped me in understanding RxSwift.

Ok, let’s try to send simple request using Alamofire and RxSwift. First we write request function:

 func getApi() -> Observable<AnyObject?> {
    return create{ observer in
        let request = Alamofire.request(.GET, "http://someapiurl.com", parameters: nil)
            .response(completionHandler:  { request, response, data, error in
                if ((error) != nil) {
                    observer.on(.Error(error!))
                } else {
                    observer.on(.Next(data))
                    observer.on(.Completed)
                }
            });
        return AnonymousDisposable {
            request.cancel()
        }
    }
}

getApi() method sends request and gets response from server using Alamofire. I used RxSwift observer for sending success or errors messages. Second we must call this function. You can use rx_tap for button:

class ViewController: UIViewController {

        var disposeBag = DisposeBag()

        override func viewDidLoad() {
            super.viewDidLoad()


            getApi()
                // Set 3 attempts to get response
                .retry(3)
                // Set 2 seconds timeout
                .timeout(2, MainScheduler.sharedInstance)
                // Subscribe in background thread
                .subscribeOn(Dependencies.sharedDependencies.backgroundWorkScheduler)
                // Observe in main thread
                .observeOn(Dependencies.sharedDependencies.mainScheduler)
                // Subscribe on observer
                .subscribe(
                    onNext: { data in
                        do {
                            let post = try NSJSONSerialization.JSONObjectWithData(data as! NSData, options: []) as! NSDictionary
                            print(post)
                        } catch  {
                            print(NSString(data: data as! NSData, encoding: NSUTF8StringEncoding))
                            return
                        }
                    },
                    onError: { error in
                        print(error)
                    },
                    onCompleted: {
                        print("Completed")
                    },
                    onDisposed: {
                        print("Disposed")
                    }
                )
                .addDisposableTo(disposeBag)
        }
    }

This is my simple example. Hope this helps you. ReactiveX is a huge opportunities. Good luck in learn RxSwift!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)