mercredi 20 janvier 2016

Using RX to communicate between two components through a mediator

C1 and C2 are components that don't know about each other. C1 does things that C2 cares about. I use a "Manager/Mediator" to allow communication between them.

Both C1 and C2 reference this mediator. C1 calls method mMediator.notifyItemProduced() and Mediator forwards an 'onItemProduced' event to any listener it has. C2 implements this listener interface and does what it wants with it.

class Mediator {
   List<Listener> mListeners;

   public void notifyItemProduced() {
        for each listener in mListeners
            listener.onItemProduced();
   }

   public void addListener(Listener listener) { ... }

   public interface Listener { 
       void onItemProduced();
   }
}

class C1 {
    public void onClick() { mMediator.notifyItemProduced(); }
}

class C2 {
    public C2 { mMediator.addListener(this); }

    public void onItemProduced() { 
        // do something here!
    }
}

I'm evaluating replacing this pattern with an RX implementation. I'm thinking that the Mediator should hold on to a Subject that C1 publishes to and C2 subscribes to.

class Mediator {
   Subject<Boolean, Boolean> mItems;

   public Subject<Boolean, Boolean> getItemsSubject() {
        return mItems;
   }

   public Observable<Booelan> getItemsStream() {
       return mItems.asObservable();
   }
}

class C1 {
    public void onClick() { mMediator.getItemsSubject().onNext(true); }
}

class C2 {
    public C2 { mMediator.getItems().subscribe(b => doSomething(b)); }
}

I don't like that the Mediator exposes to everyone the ability to publish events. Though I know this ability existed in the listener-based implementation, I'd like to know if there's a pattern that would allow:

  • C1 & C2 not knowing about each other
  • Only C1 can publish events
  • Anyone can subscribe to these events

Or is what I have a reasonable/best solution?

Aucun commentaire:

Enregistrer un commentaire