RxSwift + MVVM

RxSwift(1). RxSwift 장점, 설치

clamp 2023. 2. 16. 14:04

RxSwift는 ReactiveX라이브러리를 Swift 언어로 구현해 놓은 것.

https://github.com/ReactiveX/RxSwift

 

GitHub - ReactiveX/RxSwift: Reactive Programming in Swift

Reactive Programming in Swift. Contribute to ReactiveX/RxSwift development by creating an account on GitHub.

github.com

 

RxSwift의 장점과 사용하는 이유

간단한 샘플 코드를 제공하는데, 기존코드에 비해 얼마나 단순해 지는지를 비교해본다.

첫 번째 코드

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

두 개의 텍스트 필드에 입력된 값을 공백으로 연결하고, 문자열 앞 부분에 "Greetings, "를 추가한다. 다음 이 문자열을 lable에 나타내는 코드이다. 그리고 이 코드는 텍스트필드에 새로운 값이 입력될 때 마다 반복적으로 실행된다. 동일한 기능의 코드를 RxSwift없이 구현한다면 이렇게 3줄의 코드로 구현할 수 없다.

 

tableView와 CollectionView를 구현 할 때에도 전통적인 델리게이트 패턴을 구현하지 않고, 아래와 같이 단순한 코드로 구현할 수 있다.

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)

 

Keyvalueobserving과 Notification 또한 단순하게 구현할 수 있다.

 

모든 내용의 공통적인 내용은 RxSwift을 사용하면 간단하고 직관적인 코드로 구현할 수 있다는 것.

 

설치

CocoaPods를 통해 설치할 수 있다.

# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
    pod 'RxSwift', '6.5.0'
    pod 'RxCocoa', '6.5.0'
end

# RxTest and RxBlocking make the most sense in the context of unit/integration tests
target 'YOUR_TESTING_TARGET' do
    pod 'RxBlocking', '6.5.0'
    pod 'RxTest', '6.5.0'
end

 

RxSwift는 이름 그대로 RxSwift구현에 필요한 라이브러리이고

RxCocoa는 Cocotouch프레임워크에 Rx기능을 추가하는 라이브러리다.

팟 파일을 입력하고 터미널에서 프로젝트 폴더로 이동한 다음 pod install명령을 입력하면 설치가 완료된다.

 

애플 실리콘의 경우 

해결법
1) sudo arch -x86_64 gem install ffi
2) arch -x86_64 pod install

 

해당 프로젝트에 들어가서 작성한다.

import UIKit
import RxSwift

let disposeBag = DisposeBag()

Observable.just("Hello, RxSwift")
    .subscribe{ print($0) }
    .disposed(by: disposeBag)

를 입력했을 때 

next(Hello, RxSwift)

completed

이런 출력이 나온다면 잘 설치 된것이다.

 

처음부터 RxSwift의 모든걸 이해하고 알려 하지말자. 할 수 없다.

이해 안되는 부분은 넘어가고 다회독을 한다면 점차 이해해 나가는 영역이 넓어질것이다.