관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - SwiftUI] Combine 훑어보기 - RxSwift와의 차이점 본문

iOS Combine (SwiftUI)

[iOS - SwiftUI] Combine 훑어보기 - RxSwift와의 차이점

jake-kim 2022. 9. 14. 22:55

목차) Combine - 목차 링크

Combine과 RxSwift의 주요 차이점

  • Combine과 RxSwift 모두 Publisher, Subscriber하는 컴포넌트가 있고, stream을 만들어서 그 stream안에 operator를 사용하여 이벤트를 처리하는 형태
  • Combine은 RxSwift보다 성능이 훨씬 향상

ex) 성능 테스트

map, filter, flatMap 등을 결합한 연산자 시간과 메모리 사용량 비교

// 출처: https://medium.com/@M0rtyMerr/will-combine-kill-rxswift-64780a150d89

import XCTest
import Combine
import RxSwift

final class PlaygroundTests: XCTestCase {
    private let input = stride(from: 0, to: 10_000_000, by: 1)

    override class var defaultPerformanceMetrics: [XCTPerformanceMetric] {
        return [
            XCTPerformanceMetric("com.apple.XCTPerformanceMetric_TransientHeapAllocationsKilobytes"),
            .wallClockTime
        ]
    }

    func testCombine() {
        self.measure {
            _ = Publishers.Sequence(sequence: input)
                .map { $0 * 2 }
                .filter { $0.isMultiple(of: 2) }
                .flatMap { Publishers.Just($0) }
                .count()
                .sink(receiveValue: {
                    print($0)
                })
        }
    }

    func testRxSwift() {
        self.measure {
            _ = Observable.from(input)
                .map { $0 * 2 }
                .filter { $0.isMultiple(of: 2) }
                .flatMap { Observable.just($0) }
                .toArray()
                .map { $0.count }
                .subscribe(onSuccess: { print($0) })
        }
    }
}

테스트 결과, Combine이 시간도 적게 걸리고 메모리도 더 적게사용하여 효율적

  • Combine은 first-party 프레임워크이고, RxSwift는 third-party이므로, Combine을 사용하려면 별도의 설치 없이 바로 iOS 13+에서 사용이 가능

Combine vs RxSwift 주요 비교

  RxSwift Combine
Deployment Target iOS 8.0+ iOS 13.0 +
Framework Consumtion Third-party (RxCocoa) First-party (built-in)
  Observable Publisher
  Observer Subscriber
  SubjectType Subject
  BehaviorSubject CurrentValueSubject
  DisposeBag Cancellable
  Driver ObservaleObject
  PublishRelay X
  PublishSubject PassthroughSubject
  SchudulerType Scheduler
  Single Deferred + Future

Combine vs RxSwift Operator 비교

RxSwift Combine
asObservable() eraseToAnyPublisher()
bind(to:) assign(to:on:)
catchError catch
catchErrorJustReturn replaceError(with:)
combineLatest combineLatest, tryCombineLatest
compactMap compactMap, tryCompactMap
concat append, prepend
compactMap X
create X
debug print
distinctUntilChanged removeDuplicates, tryRemoveDuplicates
do handleEvents
elementAt output(at:)
empty Empty(completeImmediately: true)
error Fail
flatMapLatest switchToLatest
withLatestFrom X
observe(on:) receive(on:)
of Sequence.publisher
skip(3) dropFirst(3)
subscribe sink
take(1) prefix(1)
timer Timer.publish

* 참고

https://github.com/CombineCommunity/rxswift-to-combine-cheatsheet

https://medium.com/@M0rtyMerr/will-combine-kill-rxswift-64780a150d89

Comments