subscribe 이후 onError로 빠지는 에러를 핸들링하는 중 다시 API 호출을 할 경우가 생겨 onError 안에서 다시 구독을 한 경우가 생겼다. 이 경우 괜찮은 처리일까?
stackoverflow 의 답변을 보고 다시 한 번 reactive programming 그리고 functional programming 의 원리 원칙을 기억하기 위해 남기는 글
it is not good to call a subscribe inside a subscribe.
Why?
Well because this is not how functional programming is supposed to work. You're not thinking functionally you're thinking procedurally. This isn't necessarily a problem per se, but the whole point of using rxjs (and other reactive programming extensions) is to write functional code. I'm not going into all the details on what functional programming is but essentially the point of functional programming is to treat data as streams. Streams that are manipulated by functions, and consumed by subscribers. As soon as you add a subscribe inside another subscribe your manipulating data inside a consumer (not inside a stream). So your functional stream is now broken. This prevents other consumers from utilising that stream further dow in your code. So you've turned your functional stream into a procedure.
stream을 통해 데이터를 다룬 것이 아닌 consumer안에서 데이터를 다루는 것은 data를 stream으로 다뤄야하는 functional code에 위반되는 것.
함수형 프로그래밍은 데이터를 스트림으로 다루는 것을 강조한다. 함수형 프로그래밍에서 데이터는 불변적이며, 데이터를 조작하거나 변환하기 위해 함수를 사용합니다. 이것이 함수형 프로그래밍의 핵심 원칙 중 하나인 데이터 흐름을 다루는 함수이다.
리액티브 프로그래밍 역시 데이터를 스트림으로 다루는 개념을 중시한다. 리액티브 프로그래밍에서는 데이터 스트림을 조작하고 합치는 등의 작업을 수행하기 위해 다양한 연산자(operators)를 사용한다.
중첩된 subscribe을 사용하는 것은 데이터 스트림을 함수로 조작하는 대신, subscribe 블록 내에서 데이터를 다루는 절차적인 방식이다. 이로 인해 함수형 프로그래밍 및 리액티브 프로그래밍의 주요 이점 중 하나인 데이터 흐름의 불변성과 스트림 조작의 선언적 표현을 잃을 수 있다.
또한 중첩된 subscribe는 데이터 스트림을 각각의 subscribe 블록에서 처리하기 때문에, 다른 곳에서 이 스트림을 재사용하거나 조합하기가 어렵다. 이로 인해 코드의 재사용과 확장성이 저하될 수 있다.
따라서 리액티브 프로그래밍에서는 데이터 스트림을 함수적으로 조작하고 연산자를 활용하여 데이터를 다루는 것이 권장되며 중첩된 subscribe을 피하는 것이 좋다.
따라서 이같은 경우 onErrorResumeNext 와 같은 에러를 캐치해주는 Rx operator를 찾아 stream에 맞는 에러 핸들링 처리로 바꾸어 주었다.
참고자료
'💤 RxJava' 카테고리의 다른 글
[RxJava] Single, Maybe and Completable (0) | 2023.09.12 |
---|---|
[RxJava] Observable 생성하기 (0) | 2023.09.12 |
[RxJava] Observable (0) | 2023.09.12 |
[RxJava] Scheduler로 Multi Thread 관리하기 (0) | 2023.07.04 |
[RxJava] Rxjava + Retrofit = Error Handling (0) | 2023.03.31 |