# RxJava概念

主要的想法是觀察者模式(Observer Pattern)，由觀察者(Observer)及被觀察者(Observable)組成

***觀察者***&#x900F;過註冊/訂閱(Subscribe)***被觀察者***，監控被觀察者。***被觀察者***&#x53EA;要偵測到變化就會通&#x77E5;***觀察者***

***快速判斷***：要判斷觀察者和被觀察者的角色分別，就&#x770B;***哪一個是會先改變的***，會先改變的那個就&#x662F;***被觀察者***，接收被觀察者通知才改變的就&#x662F;***觀察者***。

在Java的寫法和觀念顛倒：

```
observable.subscribe(observer)
```

## Observer

針對Observable的通知行為應該要有些什麼反應

```java
Observer<String> observe = new Observer<String> {
    @Override
    public void onNext(String s) {
        Log.d(TAG, "Item: " + s);
    }
    @Override
    public void onCompleted() {
        Log.d(TAG, "Completed!");
    }
    @Override
    public void onError(Throwable e) {
        Log.d(TAG, e.getMessage());
    }
}
```

onNext() -> 接到通知以後會逐條執行的行為

onCompleted() -> 全部onNext()執行完會去執行的方法

onError() -> 執行途中發生錯誤會去執行的方法

## Observable

被觀察者如何通知觀察者

```java
Observable observable = Observable.create(new Observable.onSubscribe<String>(){
    @Override
    public void call(Subscriber<? super String> subscriber) {
        subscriber.onNext("Hello!");
        subscriber.onNext("World!");
        subscriber.onCompleted();
    }
})
```

一旦被訂閱就會觸發call()

## Subscribe

```java
observable.subscribe(observer)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yoyo840821.gitbook.io/android-learning/rxjava-gai-nian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
