Skip to content

Custom observables

myeongin edited this page Apr 22, 2016 · 41 revisions

https://github.com/google/agera/wiki/Custom-observables

Agera는 custom observable 을 정의하는데 필요한 모든것을 쉽게 제공합니다.

Proxy observables

proxy observable는 단순히 다른 observables에게 이벤트를 전달하며 processing은 거의 없다.’ utility class Observables 은 다음과 같은 표준 proxy observables 생성 방법을 제공합니다.:

  • compositeObservable 여러 source observables 들을 합성;
  • conditionalObservable 조건에 따라 source observable 에서 이벤트를 통제(filter?);
  • perMillisecondObservable and perLoopObservable source observable의 이벤트 주기를 조절.

BaseObservable

기본 class BaseObservable updatable 등록, 등록해제, notification의 모든 구현이 있고, 쓰레딩 규약을 준수한다. Subclassing(상속) 은 custom observable 을 만드는 가장 쉬운 방법이다. subclass 모든 쓰레이드에서 이벤트 전송이 필요하면 dispatchUpdate() 를 호출하기만 하면 된다. 다음 예제는 View를 클릭 이벤트를 observabl로 변환하는 예제이다.:

    public class ViewClickedObservable extends BaseObservable implements View.OnClickListener {

      @Override
      public void onClick(View v) {
        dispatchUpdate();
      }
    }

BaseObservable의 subclass는 activation lifecycle 의 시작과 끝에서 호출되며, observableActivated()observableDeactivated() 을 통해 monitor 할 수 있다. 이 두 메소드는 BaseObservable의 worker Looper thread( BaseObservable 인스턴스가 인스턴스화 하는 스레드) 에서 호출 합니다. 앱 전체 observable은 worker looper에서 호출 되기 때문에 main looper는 대부분 시나리오에서 모든 synchronization lock을 하지 않아도 된다.

UpdateDispatcher

이미 상속을 받고 있어 BaseObservable상속이 불가능할 경우가 있지만, Observable interface 를 implement 하면 된다. UpdateDispatcher instance custom observable은 쓰레딩 규약을 준수하면 BaseObservable과 같은 방법으로 updatables를 관리 할 수 있다.

custom observable은 Observables.updateDispatcher(), 또는 ActivationHandler instance를 허용하는 오버로드를 사용하여 개인 소유(privately owned)의 update dispatche 를 만들어야합니다. ActivationHandler interface 는 activation lifecycle 를 monitoring 하기 위해 observableActivatedobservableDeactivated 메소드가 정의되어 있다. BaseObservable처럼 update dispatcher가 실행되는 worker Looper 가 필요하고 그래서 Looper thread에서 생성해야 한다.

custom observable은 update dispatcher를 위해 updatable 등록과 등록해제 만 구현하면 된다. 모든 client updatables 에서 이벤트를 전달하려면 UpdateDispatcher.update() 를 호출하면 된다. custom observable 자신이 proxy observable 이고 다른 이벤트 소스에 내부 updatable을 등록 할 필요가있는 경우 update dispatcher로 updatable 를 쉽게 업데이트 할 수 있다.

추가 팁으로, UpdateDispatcher 또한 Observable 의 서브 타입이고 basic observable로써 사용 할 수 있다. 변경 가능한 repository 가 생산자 및 데이터 의 소비자 와의 bridge 역할과 마찬가지로 , update dispatcher 이벤트 의 생산자와 소비자 의 bridge 역할을 한다. data 생산자는 data를 전달하기 위해 MutableRepository interface Receiver 를 사용한다. 마찬가지로, event 생성자는 event를 전달하기 위해 UpdateDispatcher interface Updatable을 사용며, event 소비자는 Observable을 통해 events를 수신한다.

update dispatcher 샘플은 다음 페이지.