RxSwift

[iOS / RxSwift] Observable

Minny27 2022. 9. 1. 01:53

Observable

In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so.

ReactiveX에서 observer는 Observable을 구독합니다. 그런 다음 해당 observer는 Observable이 방출하는 아이템 또는 아이템 시퀀스에 반응합니다. 이 패턴은 Observable이 객체를 방출하기를 기다리는 동안 블락할 필요가 없기 때문에 동시 작업을 용이하게 하지만, 관찰자가 미래에 어떤 식으로든 적절하게 반응할 준비가 된 관찰자의 형태로 보초를 만듭니다.

 

This page explains what the reactive pattern is and what Observables and observers are (and how observers subscribe to Observables). Other pages show how you use the variety of Observable operators to link Observables together and change their behaviors.

이 페이지는 반응 패턴이 무엇인지, Observable과 Observer가 무엇인지(그리고 Observer가 Observable을 구독하는 방법)을 설명합니다. 다른 페이지에서는 다양한 Observable operator를 사용하여 Observable을 함께 연결하고 동작을 변경하는 방법을 보여줍니다.

 

This documentation accompanies its explanations with “marble diagrams.” Here is how marble diagrams represent Observables and transformations of Observables:

이 문서에는 "마블 다이어그램"과 함께 설명이 함께 제공됩니다. 다음은 마블 다이어그램이 Observable과 Observable의 변환을 나타내는 방법입니다.

Background

In many software programming tasks, you more or less expect that the instructions you write will execute and complete incrementally, one-at-a-time, in order as you have written them. But in ReactiveX, many instructions may execute in parallel and their results are later captured, in arbitrary order, by “observers.” Rather than calling a method, you define a mechanism for retrieving and transforming the data, in the form of an “Observable,” and then subscribe an observer to it, at which point the previously-defined mechanism fires into action with the observer standing sentry to capture and respond to its emissions whenever they are ready.

많은 소프트웨어 프로그래밍 작업에서 작성하는 명령이 작성한 순서대로 한 번에 하나씩 점진적으로 실행되고 완료될 것으로 예상합니다. 그러나 ReactiveX에서는 많은 명령어가 병렬(Parallel)로 실행될 수 있으며 그 결과는 나중에 "observers"에 의해 임의의 순서로 캡처됩니다. 메소드를 호출하는 대신 "Observable"의 형태로 데이터를 검색하고 변환하는 메커니즘을 정의한 다음 observer을 구독합니다. 이 지점에서 이전에 정의된 메커니즘은 observer가 서 있는 보초와 함께 동작하여 준비가 될 때마다 emission을 포착하고 대응합니다.

 

An advantage of this approach is that when you have a bunch of tasks that are not dependent on each other, you can start them all at the same time rather than waiting for each one to finish before starting the next one — that way, your entire bundle of tasks only takes as long to complete as the longest task in the bundle.

이 접근 방식의 장점은 서로 의존하지 않는 여러 작업이 있을 때 다음 작업을 시작하기 전에 각 작업이 완료되기를 기다리는 대신 동시에 모든 작업을 시작할 수 있다는 것입니다. 작업 번들은 번들에서 가장 긴 작업만큼 완료하는 데 시간이 걸립니다.

 

There are many terms used to describe this model of asynchronous programming and design. This document will use the following terms: An observer subscribes to an Observable. An Observable emits items or sends notifications to its observers by calling the observers’ methods.

이 비동기 프로그래밍 및 설계 모델을 설명하는 데 사용되는 용어가 많이 있습니다. 이 문서에서는 다음과 같은 용어를 사용합니다. observer는 Observable을 구독합니다. Observable은 항목을 내보내거나 observer의 메서드를 호출하여 observer에게 알림을 보냅니다.

 

In other documents and other contexts, what we are calling an “observer” is sometimes called a “subscriber,” “watcher,” or “reactor.” This model in general is often referred to as the “reactor pattern”.

다른 문서 및 기타 맥락에서 우리가 "observer"라고 부르는 것을 "구독자", "감시자" 또는 "반응기"라고 하는 경우가 있습니다. 일반적으로 이 모델을 "reactor pattern"이라고 합니다.

 

Establishing Observers

This page uses Groovy like pseudocode for its examples, but there are ReactiveX implementations in many languages.

이 페이지는 예제를 위해 Groovy와 유사한 의사 코드를 사용하지만 많은 언어로 ReactiveX 구현이 있습니다.

 

In an ordinary method call — that is, not the sort of asynchronous, parallel calls typical in ReactiveX — the flow is something like this:

  1. Call a method.
  2. Store the return value from that method in a variable.
  3. Use that variable and its new value to do something useful.

ReactiveX에서 일반적으로 사용되는 일종의 비동기식 병렬 호출이 아닌 일반 메서드 호출에서 흐름은 다음과 같습니다.

  1. 메서드를 호출
  2. 해당 메서드의 반환 값을 변수에 저장
  3. 해당 변수와 새 값을 사용하여 유용한 작업을 수행

 

Or, something like this:

또는 다음과 같습니다.

// make the call, assign its return value to `returnVal`
returnVal = someMethod(itsParameters);
// do something useful with returnVal

In the asynchronous model the flow goes more like this:

  1. Define a method that does something useful with the return value from the asynchronous call; this method is part of the observer.
  2. Define the asynchronous call itself as an Observable.
  3. Attach the observer to that Observable by subscribing it (this also initiates the actions of the Observable).
  4. Go on with your business; whenever the call returns, the observer’s method will begin to operate on its return value or values — the items emitted by the Observable.
    Which looks something like this:

비동기식 모델에서 흐름은 다음과 같이 진행됩니다.

  1. 비동기 호출의 반환 값으로 유용한 작업을 수행하는 메서드를 정의합니다. 이 방법은 관찰자의 일부입니다.
  2. 비동기 호출 자체를 Observable로 정의합니다.
  3. Observable을 구독하여 관찰자를 해당 Observable에 연결합니다(이는 Observable의 작업도 시작함).
  4. 작업을 계속하십시오. 호출이 반환될 때마다 관찰자의 메서드는 반환 값(Observable에서 내보낸 항목)에 대해 작동하기 시작합니다.
    다음과 같이 보입니다.

 

// defines, but does not invoke, the Subscriber's onNext handler
// (in this example, the observer is very simple and has only an onNext handler)
def myOnNext = { it -> do something useful with it };
// defines, but does not invoke, the Observable
def myObservable = someObservable(itsParameters);
// subscribes the Subscriber to the Observable, and invokes the Observable
myObservable.subscribe(myOnNext);
// go on about my business

 

onNext, onCompleted, and onError

The Subscribe method is how you connect an observer to an Observable. Your observer implements some subset of the following methods:

구독 방법은 관찰자를 관찰자에 연결하는 방법입니다. 관찰자는 다음 메서드의 일부 하위 집합을 구현합니다.

 

onNext

  • An Observable calls this method whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable.

Observable은 Observable이 항목을 방출할 때마다 이 메서드를 호출합니다. 이 메소드는 Observable이 내보낸 항목을 매개변수로 사용합니다.

 

onError

  • An Observable calls this method to indicate that it has failed to generate the expected data or has encountered some other error. It will not make further calls to onNext or onCompleted. The onError method takes as its parameter an indication of what caused the error.

Observable은 이 메서드를 호출하여 예상 데이터 생성에 실패했거나 다른 오류가 발생했음을 나타냅니다. onNext 또는 onCompleted를 더 이상 호출하지 않습니다. onError 메서드는 매개변수로 오류를 일으킨 원인을 나타냅니다.

 

onCompleted

  • An Observable calls this method after it has called onNext for the final time, if it has not encountered any errors.

Observable은 오류가 발생하지 않은 경우 마지막으로 onNext를 호출한 후 이 메서드를 호출합니다.

 

By the terms of the Observable contract, it may call onNext zero or more times, and then may follow those calls with a call to either onCompleted or onError but not both, which will be its last call. By convention, in this document, calls to onNext are usually called “emissions” of items, whereas calls to onCompleted or onError are called “notifications.”

Observable 조건에 따라 onNext를 0번 이상 호출한 다음 해당 호출에 따라 onCompleted 또는 onError 중 하나를 호출할 수 있지만 둘 다 호출할 수는 없습니다. 이 호출은 마지막 호출이 됩니다. 관례에 따라 이 문서에서 onNext에 대한 호출은 일반적으로 항목의 "방출"이라고 하는 반면 onCompleted 또는 onError에 대한 호출은 "알림"이라고 합니다.

 

A more complete subscribe call example looks like this:

보다 완전한 구독 호출 예는 다음과 같습니다.

def myOnNext     = { item -> /* do something useful with item */ };
def myError      = { throwable -> /* react sensibly to a failed call */ };
def myComplete   = { /* clean up after the final response */ };
def myObservable = someMethod(itsParameters);
myObservable.subscribe(myOnNext, myError, myComplete);
// go on about my business

 

Unsubscribing

In some ReactiveX implementations, there is a specialized observer interface, Subscriber, that implements an unsubscribe method. You can call this method to indicate that the Subscriber is no longer interested in any of the Observables it is currently subscribed to. Those Observables can then (if they have no other interested observers) choose to stop generating new items to emit.

일부 ReactiveX 구현에는 구독 취소 메서드를 구현하는 특수 observer 인터페이스인 Subscriber가 있습니다. 구독자가 현재 구독 중인 Observable에 더 이상 관심이 없음을 나타내기 위해 이 메서드를 호출할 수 있습니다. 그런 다음 해당 Observable은 (관심 있는 다른 observer가 없는 경우) 방출할 새 아이템 생성을 중지하도록 선택할 수 있습니다.

 

The results of this unsubscription will cascade back through the chain of operators that applies to the Observable that the observer subscribed to, and this will cause each link in the chain to stop emitting items. This is not guaranteed to happen immediately, however, and it is possible for an Observable to generate and attempt to emit items for a while even after no observers remain to observe these emissions.

이 구독 취소의 결과는 관찰자가 구독한 Observable에 적용되는 연산자 체인을 통해 다시 캐스케이드백되며 이로 인해 체인의 각 링크에서 항목 방출이 중지됩니다. 그러나 이것은 즉시 발생한다고 보장되지 않으며 이러한 방출을 관찰할 observer가 남아 있지 않은 후에도 잠시 동안 Observable이 항목을 생성하고 방출을 시도할 수 있습니다.

 

Some Notes on Naming Conventions(네이밍 규칙 참고 사항)

Each language-specific implementation of ReactiveX has its own naming quirks. There is no canonical naming standard, though there are many commonalities between implementations.

ReactiveX의 각 언어별 구현에는 고유한 이름 지정 문제가 있습니다. 구현 간에 많은 공통점이 있지만 정식 명명 표준은 없습니다.

 

Furthermore, some of these names have different implications in other contexts, or seem awkward in the idiom of a particular implementing language.

또한 이러한 이름 중 일부는 다른 컨텍스트에서 다른 의미를 갖거나 특정 구현 언어의 관용구에서 어색해 보입니다.

 

For example there is the onEvent naming pattern (e.g. onNext, onCompleted, onError). In some contexts such names would indicate methods by means of which event handlers are registered. In ReactiveX, however, they name the event handlers themselves.

예를 들어 onEvent 이름 지정 패턴이 있습니다(예: onNext, onCompleted, onError). 일부 컨텍스트에서 이러한 이름은 이벤트 핸들러가 등록되는 방법을 나타내는 메서드를 나타냅니다. 그러나 ReactiveX에서는 이벤트 핸들러 자체의 이름을 지정합니다.

 

“Hot” and “Cold” Observables

When does an Observable begin emitting its sequence of items? It depends on the Observable. A “hot” Observable may begin emitting items as soon as it is created, and so any observer who later subscribes to that Observable may start observing the sequence somewhere in the middle. A “cold” Observable, on the other hand, waits until an observer subscribes to it before it begins to emit items, and so such an observer is guaranteed to see the whole sequence from the beginning.

Observable은 언제 항목 시퀀스를 방출하기 시작합니까? Observable에 따라 다릅니다. "hot" Observable은 생성되자마자 항목을 방출하기 시작할 수 있으므로 나중에 해당 Observable을 구독하는 모든 관찰자는 중간 어딘가에서 시퀀스를 관찰하기 시작할 수 있습니다. 반면에 "cold" Observable은 항목을 방출하기 시작하기 전에 관찰자가 구독할 때까지 기다리므로 그러한 관찰자는 처음부터 전체 시퀀스를 볼 수 있습니다.

 

In some implementations of ReactiveX, there is also something called a “Connectable” Observable. Such an Observable does not begin emitting items until its Connect method is called, whether or not any observers have subscribed to it.

ReactiveX의 일부 구현에는 "Connectable" Observable이라는 것도 있습니다. 그러한 Observable은 observer가 구독했는지 여부에 관계없이 Connect 메서드가 호출될 때까지 항목을 방출하기 시작하지 않습니다.

 

Composition via Observable Operators(관찰 가능한 연산자를 통한 구성)

Observables and observers are only the start of ReactiveX. By themselves they’d be nothing more than a slight extension of the standard observer pattern, better suited to handling a sequence of events rather than a single callback.

Observable과 Observer는 ReactiveX의 시작일 뿐입니다. 그 자체로는 표준 관찰자 패턴의 약간의 확장일 뿐이며 단일 콜백보다 일련의 이벤트를 처리하는 데 더 적합합니다.

 

The real power comes with the “reactive extensions” (hence “ReactiveX”) — operators that allow you to transform, combine, manipulate, and work with the sequences of items emitted by Observables.

진정한 힘은 Observable에서 내보낸 아이템 시퀀스를 변환, 결합, 조작 및 작업할 수 있는 "reactive extensions"(따라서 "ReactiveX")과 함께 제공됩니다.

 

These Rx operators allow you to compose asynchronous sequences together in a declarative manner with all the efficiency benefits of callbacks but without the drawbacks of nesting callback handlers that are typically associated with asynchronous systems.

이러한 Rx 연산자를 사용하면 콜백의 모든 효율성 이점과 함께 선언적 방식으로 비동기 시퀀스를 함께 구성할 수 있지만 일반적으로 비동기 시스템과 관련된 중첩 콜백 핸들러의 단점이 없습니다.

 

 

 

※ 참고 출처

ReactiveX 공식 문서

 

ReactiveX - Observable

Observable In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Ob

reactivex.io

'RxSwift' 카테고리의 다른 글

[iOS / RxSwift] Subject  (0) 2022.09.13
[iOS / RxSwift] Single  (1) 2022.09.12
[iOS / RxSwift] Operators  (0) 2022.09.02