nus-cs2103-AY1718S1 / forum

Discussion Forum
5 stars 0 forks source link

Question about event-driven architecture in AB4 #140

Closed zenghou closed 6 years ago

zenghou commented 6 years ago

Hello all,

I am currently working on user authentication. The rough outline is to have create a UserCreds object within ModelManager. When the login command is successfully executed, a boolean attribute isValidated that is within UserCreds is changed to true. Upon this change, I want to get UIManager to execute a method.

I looked at ModelManager and had an idea about raising an event. However, I'm slightly confused as to how the UiManager is informed of this event. Can someone kindly enlighten me? If i'm on the wrong path, can someone kindly tell me how else I can get the UI to respond to a change in the Model?

Any help here would be greatly appreciated! Thanks!

philemontan commented 6 years ago

Hey, This was actually covered in the original ADB4 dev guide:

image

So Google's EventBus is used to handle this in ADB4. The EventsCenter class provides a few simple methods for you to use. The thing to note about this event-driven design, is that neither the firer or the handler require any knowledge of the other party.

Here's an example

To fire the event

  1. Import the EventsCentre class and use its .getInstance().post() method image

To handle the event:

  1. You need to first register the class as an event handler, by using the following method (you can call this in a constructor): EventsCenter.getInstance().registerHandler(this);

  2. Simply add the annotation @Subscribe (be sure to make the necessary import of, com.google.common.eventbus.Subscribe) on top of the handling method in the class that you wish for the event to be handled. Include the Event class to be handled as a parameter for this method(it should be the only parameter, since you should never have to call this method explicitly): image

zenghou commented 6 years ago

@philemontan Hey Philemon, thanks for this clarification! It helped me get to what I was looking for. I overlooked the dev guide but I'll be sure to check it next time.

damithc commented 6 years ago

Kudos for the excellent answer @philemontan 💯