상세 컨텐츠

본문 제목

[RxSwift] Basic.1

iOS/RxSwift

by kimrindev 2024. 11. 28. 21:00

본문

Basic_1

The equivalence of observer pattern (`Observable<Element>` sequence) and normal sequences (`Sequence`) 
is the most important thing to understand about Rx.


 RxSwift에서 Observable <Element> 시퀀스가 일반적인 Sequence (예: 배열 등)와 어떻게 유사한지를 이해하는 것이 매우 중요합니다. 

 

 

Every `Observable` sequence is just a sequence. The key advantage for an `Observable` vs Swift's `Sequence` is that it can also receive elements asynchronously. This is the kernel of RxSwift, documentation from here is about ways that we expand on that idea.

 

모든 Observable 시퀀스는 단지 시퀀스입니다. Observable과 Swift의 시퀀스간의 주요 장점은 Observable이 비동기적으로 요소를 받을 수 있다는 것입니다. 이것이 RxSwift의 핵심이며, 여기서부터는 이 아이디어를 확장하는 방법에 대한 문서입니다.”

 

 

 

Observable(ObservableType) is equivalent to Sequence
“Observable(ObservableType)는 Sequence와 동등하다.

ObservableType.subscribe method is equivalent to `Sequence.makeIterator` method.
ObservableType의 subscribe 메서드는 Sequence의 makeIterator 메서드와 동등하다.

Observer (callback) needs to be passed to ObservableType.subscribe method to receive sequence elements instead of calling next() on the returned iterator.
“Observer(콜백)는 ObservableType의 subscribe 메서드에 전달되어 시퀀스 요소를 받기 위해 필요하다. 반환된 반복자에서 next()를 호출하는 대신에.”

 

 

Sequences are a simple, familiar concept that is easy to visualize.
People are creatures with huge visual cortexes. When we can visualize a concept easily, it's a lot easier to reason about it.


“시퀀스는 단순하고 익숙한 개념으로 쉽게 시각화할 수 있습니다. 사람들은 시각적 피질이 매우 큰 생물입니다. 개념을 쉽게 시각화할 수 있을 때, 이를 이해하는 것이 훨씬 쉬워집니다.  (마블 다이어그램 링크)

 

 

We can lift a lot of the cognitive load from trying to simulate event state machines inside every Rx operator onto high level operations over sequences.

 

우리는 모든 Rx 연산자에서 이벤트 상태 머신을 시뮬레이션하려는 인지적 부담을 덜어낼 수 있으며, 시퀀스를 사용하여 고수준의 연산을 수행할 수 있습니다.” (복잡한 이벤트 상태를 일일히 추적하지 않아도 된다)

 

 

여기에서 독자가 말하는 인지적 부담을 덜어낼수 있다는 말의 의미는 

보통 observable은 어떤 event 를 emit 하고 나서 

  • onNext,onCompleted,onError로 상태를 추적해서 관리하는것은 개발자가 그것에대한 대응을 직접 핸들링 해야되는 resourceCost가 들지만
    (상태의 명시적인 호출과, 상태를 계속 추적하며 그에따라 필요한 동작을 일일히 작성해야하는 resource cost ) 
  • 그와 반대로  operator를 사용하게될경우 일일히 상태 관리와 흐름이 자동으로 이뤄지기에 이벤트의상태의 하나하나를 신경쓰지 않아도 된다. 

 

즉 새로운데이터가 오는경우 onNext로, 오류가 발생할시 onError로, 완료될시 onCompleted로 자동 상태 전이를 한다고 이해하였다.

 

결론이 무엇이냐?

 

즉 opeartor를 사용하지 않고 직접 방출을 관리하게 되는 경우에는
데이터를 방출하는 시점마다 onNext, onError, onCompleted 상태를 직접 호출하여 방출해야하는것이고
상태가 변화할 때마다 그에 맞는 처리를 일일이 각 단계에서 직접 제어해야 한다.

허나 연산자를 사용하게 될경우 중간단계에서 상태관리를 자동화 할수 있어서 각 연산자가 자동으로 데이터를 전달하고
오류, 완료 상태를 다음 연산자로 넘기기 때문에,매번 방출을 직접 관리할 필요가 없고

최종 subscribe에서만 최종 데이터와 상태(onNext, onError, onCompleted)를 구독하여
한 번만 처리해주면 된다는게 이말의 요지이다.

 

 

 

RxMarbles: Interactive diagrams of Rx Observables

 

rxmarbles.com

 

 

'iOS > RxSwift' 카테고리의 다른 글

[RxSwift] Scheduler.2  (1) 2024.12.16
[RxSwift] Scheduler.1  (2) 2024.12.12
[RxSwift] DesignRationale  (3) 2024.12.08
[RxSwift] Basic.2  (3) 2024.11.29
[RxSwift] Obsevables aka sequence  (1) 2024.11.27

관련글 더보기