Monti

Swift) RxSwift 기초 (MVVM, 비동기적 라이브러리 사용) 본문

IOS/Swift

Swift) RxSwift 기초 (MVVM, 비동기적 라이브러리 사용)

montt 2022. 10. 23. 16:10

RxSwift란? (RxSwift GitHub)


Rx is a generic abstraction of computation expressed through Observable<Element> interface, which lets you broadcast and subscribe to values and other events from an Observable stream.

RxSwift의 의도는 비동기 작업과 Observable 의 비동기 작업 조각을 변환하고 구성하는 일련의 메서드와 개체 형태의 데이터 스트림을 쉽게 구성할 수 있도록 도와준다.

*Rx Swift의 핵심

비동기&이벤트의 표현 ⇒ 관찰 가능한 순차적인 형태, 함수형태의 연산자

RxSwift 를 사용하는 이유

  1. Swift 비동기 실행
    1. 애플에서 제공해주는 Delegate 패턴을 사용 할 경우, 해당 Delegate의 코드를 파악하기 어려움
    2. 비동기 실행에 관하여 명확한 추론에 대한 어려움
    3. 해당 버튼이 몇번 호출이되었는지, 코드상에서 실시간적으로 확인이 어려움
  2. MVVM 패턴과의 연관 (스위프트 패턴 : Swift Architecture)
    1. MVVM의 배경 : 데이터 바인딩을 제공하는 플렛폼에서 만들어진 이벤트 중심 프로그램을 위해 개발
    2. RxSwift는 MVVM 패턴의 형식을 가지고 있음

RxSwift의 필요성

  1. 명시적으로 공유된 mutable state 를 파악하기 위함
  2. imperative Programming(명시적 코드)의 한계 극복
  3. Side Effects를 통해 state 파악
  4. Declarative code(선언적 코드)
  5. Reactive System

RxSwift 3가지 요소


1. Observalbles

  • Rx 코드의 기반
  • T 형태의 데이터 snapshot을 ‘전달’할 수 있는 일련의 이벤트를 비동기적으로 생성하는 기능
  • 하나 이상의 observers가 실시간으로 어떤 이벤트에 반응
  • 세 가지 유형의 이벤트만 방출 (next, error, complete)
enum Event<Element> {
    case next(Element)          // next element of a sequence
    case error(Swift.Error)     // sequence failed with error
    case completed              // sequence terminated successfully
}
  • example
// 다운로드
API.download(file: "http://www...")
	.subscribe(onNext: { data in
		// Append data to temporary file
	},
	onError : { error in
		// Display error to user
	},
	onCompleted: {
		// Use downloaded file
	})

// Device 가로모드 / 세로모드
UIDevice.rx.orientation
	.subscribe(onNext: { current in
		switch current {
		case .landscape:
				// 가로모드 배치
		case .portrait:
				// 세로모드 배치
		}
	})

 

2. Operator

  • 마치 연산자와 같이 옵저버에서 나온 결과물을 Rx연산자를 통해 입력 및 출력이 가능 → side effect발생 가능
  • showAlert과 같이 옵저버에서 나온 결과에서 Rx연산자를 사용하여 경고문 발생
UIDevice.rx.orientation
    .filter { value in
        return value != .landscape
    }
    .map { _ in
            return "세로로만 봄"
    }
    .subscribe(onNext: { string in
            showAlert(text: string)
    })

3.Schedulers

  • 기존의 DispatchQueue와 동일한 기능

 

RxSwift 설치


설치 요구사항

  • Xcode 12.x 이상
  • Swift 5.x 이상

CocoaPod 설치 (공식문서)

# 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] 1. RxSwift의 개념

Comments