Observer Pattern

2019. 4. 19. 16:56Android

반응형
1)

  public interface ObserverListener {
    void register(Observer observer);
    void unregister(Observer observer);
    void notifyObserver();
  }

2)

  public interface Observer {
    void update();
  }

3) MainActivity

   public class MainActivity implements Observer {
          ......
    TestFragment fragment = new TestFragment();
    fragment.register(this); // add Observer
          ......
    @Override
    public void update() {
        // update  , unregister
    }
    
   }

   
4) TestFragment 
   public class TestFragment implements ObserverListener{
          ......
    private List mObservers = new ArrayList<>();

    @Override
    public void onStart() {
        super.onStart();
        notifyObserver();
    }

    @Override
    public void register(Observer observer) {
        if(mObservers != null && !mObservers.contains(observer))
            mObservers.add(observer);
    }

    @Override
    public void unregister(Observer observer) {
        if (mObservers != null)
            mObservers.remove(observer);
    }

    @Override
    public void notifyObserver() {
        for(Observer observer : mObservers){
            observer.update();
        }
    }
    
   }



https://stackoverflow.com/questions/42983101/using-observable-in-android

 

Using Observable in Android

I want to implement a Navigation View with many fragments that depend totally on a value defined in the MainActivity. I know that variables in MainActivity can be accessed using method defined in

stackoverflow.com

 

반응형

'Android' 카테고리의 다른 글

Letter spacing  (0) 2019.05.23
BottomDialog  (0) 2019.04.22
안드로이드 파이 대응 관련  (0) 2019.04.18
android-design-support-library  (0) 2019.04.18
안드로이드 아키텍처 컴포넌트  (0) 2018.12.30