Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift minimal Observable.create example

Tags:

swift

rx-swift

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) 
like image 620
Matthijn Avatar asked Jan 13 '16 16:01

Matthijn


People also ask

What is RxSwift observable?

The heart of the RxSwift framework is based on observable which is also known as a sequence. Observable is the sequence of data or events which can be subscribed and can be extended by applying different Rx operators like map, filter, flatMap, etc. It can receive data asynchronously.

What is Onnext in RxSwift?

Called by the Observable when it emits an item. Takes as a parameter the item emitted by the Observable. Calls are referred to as emissions .


2 Answers

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!

like image 79
Svyatoslav Avatar answered Sep 22 '22 14:09

Svyatoslav


This implementation has changed slightly with Swift 3:

    func observableFunc() -> Observable<Bool> {         return Observable.create { observer in              self.apiClient.fetchData(callback: { results, error in                  if let error = error {                     observer.onError(error)                 }                  if let results = results {                     observer.onNext(true)                     observer.onCompleted()                 }             })             return Disposables.create()         }     } 
like image 28
Gregg Avatar answered Sep 26 '22 14:09

Gregg