Matthijn Matthijn - 1 year ago 190
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

return AnonymousDisposable { }

let exampleObserver : AnyObserver<String>?

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


let ex = Example()

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


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

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

Answer Source

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, "", parameters: nil)
            .response(completionHandler:  { request, response, data, error in
                if ((error) != nil) {
                } else {
        return AnonymousDisposable {

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

                // Set 3 attempts to get response
                // Set 2 seconds timeout
                .timeout(2, MainScheduler.sharedInstance)
                // Subscribe in background thread
                // Observe in main thread
                // Subscribe on observer
                    onNext: { data in
                        do {
                            let post = try NSJSONSerialization.JSONObjectWithData(data as! NSData, options: []) as! NSDictionary
                        } catch  {
                            print(NSString(data: data as! NSData, encoding: NSUTF8StringEncoding))
                    onError: { error in
                    onCompleted: {
                    onDisposed: {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download