RxSwift

RxSwift란?

motosw3600 2022. 2. 7. 18:38

ReactiveX란?

https://reactivex.io/

 

ReactiveX

CROSS-PLATFORM Available for idiomatic Java, Scala, C#, C++, Clojure, JavaScript, Python, Groovy, JRuby, and others

reactivex.io

  • ReactiveX는 obsevable sequence를 사용하여 비동기 및 이벤트 기반 프로그램을 구성하기 위한 라이브러리
  • observer pattern을 사용하여 여러가지 기능 문제를 해결해주는 operator들을 지원
  • 함수형 프로그래밍(FP)에 반응형 프로그래밍(Reactive Programming)이 더해져 FRP프로그래밍을 지원
  • RxSwift는 ReactiveX를 도입한 Swift 개발을 위한 Base가 되는 라이브러리

Observable pattern이란

  • ReativeX Observable모델을 사용하면, 배열과 같은 데이터 항목 모음에 사용하는 것과 동일한 종류의 simple하고 composable한 작업으로 비동기 이벤트 스트림을 처리할 수 있다.

왜 RxSwift를 사용하나?

선언적으로 app을 build할 수 있다.

Bindings

Observable.combineLatest(firstName.rx.text, lastName.rx.text) { $0 + " " + $1 }
    .map { "Greetings, \($0)" }
    .bind(to: greetingLabel.rx.text)

UITableView와 UICollectionView에서도 사용 가능

viewModel
    .rows
    .bind(to: resultsTableView.rx.items(cellIdentifier: "WikipediaSearchCell", cellType: WikipediaSearchCell.self)) { (_, viewModel, cell) in
        cell.title = viewModel.title
        cell.url = viewModel.url
    }
    .disposed(by: disposeBag)

Retires

API가 실패할 경우 Rx를 사용하여 간단하게 retry가 가능하다.

// API request
func doSomethingIncredible(forWho: String) throws -> IncredibleThing
// RxSwift retry
doSomethingIncredible("me")
    .retry(3)

Delegate

기존 Delegate 코드는 지루하고 expressive하지 않다.

public func scrollViewDidScroll(scrollView: UIScrollView) { [weak self] // what scroll view is this bound to?
    self?.leftPositionConstraint.constant = scrollView.contentOffset.x
}

 

Rx를 사용하여 나타내면

self.resultsTableView
    .rx.contentOffset
    .map { $0.x }
    .bind(to: self.leftPositionConstraint.rx.constant)

Notifications

일반적인 Notification사용

@available(iOS 4.0, *)
public func addObserverForName(name: String?, object obj: AnyObject?, queue: NSOperationQueue?, usingBlock block: (NSNotification) -> Void) -> NSObjectProtocol

 

Rx사용

NotificationCenter.default
    .rx.notification(NSNotification.Name.UITextViewTextDidBeginEditing, object: myTextView)
    .map {  /*do something with data*/ }
    ....

 

위와같이 많은 코드들을 선언적으로 사용할 수 있고 읽기 쉽게 사용이 가능하다.

RxSwift의 필요성

  1. 비동기 이벤트의 흐름을 쉽게 파악하고 작성할 수 있다. ->RxSwift를 사용하지 않는다면 여러 스레드간의 클로저 이벤트 처리나 콜백지옥으로 코드가 복잡하고 가독성이 떨어질 수 있다.
  2. 비동기 처리를 Observable을 사용하여 구현할 수 있다.
  3. MVVM Design Pattern과 같이 사용하여 이벤트 중심 프로그램에서 데이터의 바인딩을 쉽게 처리할 수 있다.

 

참고: RxSwift github

 

 

'RxSwift' 카테고리의 다른 글

RxFlow  (0) 2022.03.30
RxViewController  (0) 2022.03.03
Operator  (0) 2022.02.09
Subject  (0) 2022.02.08
Observable  (0) 2022.02.07