Saturday 10 June 2017

Reactive Programming for Swift programmer



Most programmer will have no idea what reactive programming actually is. This is the reason why I will try to create a simple, how to use use the Swift Version of Rx: RxSwift. link: https://github.com/ReactiveX/RxSwift

its works on two things: Observable &  Observer
    •    An Observable is something which emits notifications of change.
    •    An Observer or subscriber is something which subscribes to an Observable, in order to get receive notification

Firstly add following line in your pod file
    pod 'RxSwift',    '~> 3.0'
    pod 'RxCocoa',    '~> 3.0' and run pod install command on terminal



To deal with ARC and memory management RxSwift and RxCocoa use: the DisposeBag. This is a virtual “bag” of Observer objects which are disposed of when their parent object is deallocated.
Here is few Example how to use RXswift
1. searchBar with RX

  @IBOutlet weak var searchBarArtist: UISearchBar!
  override func viewDidLoad() {
        super.viewDidLoad()
        searchBarArtist
            .rx.text // Observable property
            .orEmpty // Make it non-optional
            .debounce(0.3, scheduler: MainScheduler.instance) // Wait 0.3 for changes.
            .distinctUntilChanged() // If they didn't occur, check if the new value is the same as old.
            .subscribe(onNext: { query in // Here we subscribe to every new value
               
            })
            .addDisposableTo(disposeBag)
}

2. TextField with RX

let searchTxtField = UITextField()
let disposeBag = DisposeBag()
override func viewDidLoad() {

searchTxtField.rx.text.orEmpty.debounce(0.2, scheduler: MainScheduler.instance).distinctUntilChanged().subscribe(onNext: { [unowned self] query in
           
            print(query)

        }).disposed(by: disposeBag)
}

3. DataBinding with RX
    let displayLabel = UILabel()
    @IBOutlet weak var searchTxtField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
       
        searchTxtField.rx.text.map { "Hello \(String(describing: $0))" }
            .bind(to: displayLabel.rx.text)
    }


4. Control Events with RX

let button = UIButton()
var disposeBag = DisposeBag()
override func viewDidLoad() {
        super.viewDidLoad()
       
        button.rx.tap.subscribe(onNext: { [unowned self] query in
           
            print(query)
           
        }).disposed(by: disposeBag)
 }



Happy Coding!!!

#Xcode9 #iOS #Apple #Coding #iPhone
© 2017 Girijesh
In case if any query/Concern send me a email @girijeshkumar2007@gmail.com