Matthijn Matthijn - 14 days ago 19
Swift Question

RxSwift minimal Observable.create example

Currently I am trying to get RxSwift working. And I want to create a custom Observable. But I think I am doing something wrong.

I have distilled what I do to this minimal sample:

import Foundation
import RxSwift

class Example
{

let exampleObservable : Observable<String> = Observable.create { (observer) in
observer.on(.Next("hello"))
observer.on(.Completed)

return AnonymousDisposable { }
}

let exampleObserver : AnyObserver<String>?

func run()
{
self.exampleObserver = exampleObservable.subscribeNext({ (text) -> Void in
print(text)
})
}

}

let ex = Example()
ex.run()


Is this correct? In the run method, the subscribeNext method is autocompleted that way by XCode.

Example

But when I run it I get the following compilation error:

Cannot Invoke 'substribeNext' with an argument list of type ((String) -> Void)

Answer

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 to call this function. You may 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!