3 Replies Latest reply on Feb 27, 2010 6:24 PM by chasetec

    Event ordering

    chasetec
      The spec states: "The order in which observer methods are called is not defined, and so portable applications should not rely upon the order in which observers are called."

      It doesn't say that a portable applications should not rely upon the execution of observer methods but without some basic rules about ordering you may have an inconsistent number of observers fired. Take the following example:

      @RequestScoped
      public class ColorChangeConsumer {
          public void onColorChangeA(@Observes(notifyObserver=IF_EXISTS) Color color) {
              System.out.println("onColorChangeA:" + color);
          }

          public void onColorChangeB(@Observes Color color) {
              System.out.println("onColorChangeB:" + color);
          }
      }

      Depending on which observer method the IF_EXISTS value is placed on you may get one or both observer methods being called. It depends on the order of the (attempted) method calls. It seems to me that this could vary per CDI implementation.

      The order needs to be defined (conditional observers last) or there needs to be a limit of one observer method per class. Either that or mention this edge case in the docs.

      Personally I'd prefer if there was only one observer method allowed per class and then ordering of observer invocation was defined in beans.xml.

      What was the reasoning behind the lack of order anyway? I could understand that if everything was asynchronous but that isn't the case here.
        • 1. Re: Event ordering
          nickarls

          I wonder if it would be possible to write an event sorter extension? It would take over the observation role and re-fire to the methods in the order specified.

          • 2. Re: Event ordering
            gavin.king

            Your next challenge is to come up with a non-totally-contrived example of with bad behavior.


            Observers should be written to be independent and not have side-effects upon each other. That's really an essential part of the observer/observable pattern.

            • 3. Re: Event ordering
              chasetec

              I did say it was an edge case :)


              I still don't think it would be that uncommon a thing for a programmer new to CDI to run into and it is something that could be easily addressed.