RxSwift and its advantages in reactive app development.

  • Posted by:

    Madesan V

    • August 22, 2018

    RxSwift and its advantages in reactive app development.

Introduction:

Rx-Swift is a reactive programming library in iOS app development. It is a multi-platform standard, its difficult-to-handle asynchronous code in Swift, that becomes much easier in Rx-Swift.

RxSwift makes easy to develop dynamic applications that respond to changes in data and respond to user events. Ultimately, it solves the issues related to asynchronous development.

Related Terms for RxSwift:

You can say RxSwift is:

1. Functional reactive programming (FRP)
2. Reactive Programming
3. Functional Programming
4. An Observable.
5. An Observer.
6. A Dispose bag.

1. Functional Programming:

Functional programming is an alternative to imperative coding. It allows us to express the system code logic from mathematical relations (e.g. functions) instead of a strict sequence of actions.

For e.g.

People feel very guilty to write code like the sample below with normal swift programming.

Alamofire.request(.POST, “SignUp”, parameters: ["userName": "maddy”, "passWord": “12345678”])
  .responseJSON(completionHandler: { (firedResponse) -> Void in
    Alamofire.request(.GET, “UserInfo” + firedResponse.result.value)
      .responseJSON(completionHandler: { myUserInfoResponse in
        Alamofire.request(.GET, “EmployeeList” + myUserInfoResponse.result.value)
          .responseJSON(completionHandler: { friendListResponse in
            Alamofire.request(.GET, “PresentEmployees” + friendListResponse.result.value)
              .responseJSON(completionHandler: {
              })
            })
          })
    Alamofire.request(.GET, “AccountDetails” + firedResponse.result.value)
      .responseJSON(completionHandler: {
      })
    })

Any guesses, what’s wrong in this code? There are multiple Alamofire requests, and if you are not using Alamofire it will be like AFNetworking with HTTP requests. Have you ever seen nested block-based code working the way you intended? You can’t tell what will happen during run-time.

You can create multiple functions in RxSwift instead of using nested block-based code like below:

func rx_login(userName: String, passWord: String) -> Observable {
  return create({ (observer) -> Disposable in
    let postBody = [
      "userName": userName,
      "passWord": passWord
    ]
    let request = Alamofire.request(.POST, "login", parameters: postBody)
      .responseJSON(completionHandler: { (firedResponse) -> Void in
        if let value = firedResponse.result.value {
          observer.onNext(value)
          observer.onCompleted()
        } else if let error = firedResponse.result.error {
          observer.onError(error)
        }
      })
    return AnonymousDisposable{
      request.cancel()
    }
  })
}

2. Reactive Programming:

i. Reactive programming is about writing code that knows how to react to new changes dynamically like new user input or data and changes of the new states.

ii. Reactive programming will automatically change all the variables attached to the changes in the performance of an application over run-time.

3. Observable:

i. Observables are a type-safe event that fire and push different data values over run-time. Observables are something which emit the notifications of a change.

ii. Observables is easy to create.

Just(5) // Observable

If you needed to take an array from the events, we can do like this.

[1,2,3,4,5,6,7,8].toObservable() // Observable

If you want to create something like an API, which will upload some files to server or saves data in local database swell.

create { (observer: AnyObserver) -> Disposable in
  return AnonymousDisposable {
  }
}

4. Observer:

i. Observer is something which informs an observable about new changes.

ii. We can have multiple Observers to listen for a single observable, so that when the observable get changed it will notify all the observers at the same time.

5. Dispose bag:

RxSwift have an additional tool to help deal with ARC and Memory Management which is called DisposeBag.

i. This is a virtual bag of Observer objects which are disposed when the parent object is deallocated.

ii. When the deinit() method is scaled on the parent object which has a disposeBag as a property, the bag is emptied, and each disposable observer is automatically unsubscribed.

Additional features:

i. FRP is a tool for composing asynchronous and event-based programs with the help of observable sequences.

ii. There’s no need to worry about synchronisation, low-level threading, non-blocking I/O, thread safety, and concurrent data structures.

iii. The ‘observable’ can be employed as a universal, highly-compostable pattern. This way, you won’t have to use tons of patterns like completion blocks, target actions, delegations, and many others all at once.

Which cases we can use RxSwift?

i. When there is frequent necessity to use KVO.

ii. To synchronize two requests.

iii. When you don’t want to busy yourself with delegates.

iv. To create modular code.

Conclusion:

As I said earlier, RxSwift is a reactive programming language so we can use this for small applications like small games. If we use this in bigger applications we have to dispose all the objects manually, like objective-c.

Read Next

Machine learning for mobile app developers

Posted by:

Adhish L

Read More Blogs

TOP

Next Blog Last Blog All Blogs