active_events.erl 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. -module(active_events).
  2. -behaviour(gen_event).
  3. -export([
  4. start_link/0,
  5. subscribe_onload/1,
  6. subscribe_onnew/1,
  7. notify_reload/1,
  8. subscribe/2
  9. ]).
  10. -export([
  11. init/1,
  12. handle_event/2,
  13. handle_call/2,
  14. handle_info/2,
  15. terminate/2,
  16. code_change/3
  17. ]).
  18. -type mf() :: {M :: module(), F :: atom()}.
  19. -spec subscribe_onload(Function :: mf()) -> ok.
  20. -spec subscribe_onnew(Function :: mf()) -> ok.
  21. -spec subscribe(Event :: reloaded | loaded_new, Function :: mf()) -> ok.
  22. -record(event_state, {
  23. event :: reloaded | loaded_new,
  24. function :: mf()
  25. }).
  26. start_link() ->
  27. gen_event:start_link({local, ?MODULE}).
  28. subscribe_onload(Function) ->
  29. subscribe(reloaded, Function).
  30. subscribe_onnew(Function) ->
  31. subscribe(loaded_new, Function).
  32. subscribe(Event, Function) ->
  33. ok = gen_event:add_sup_handler(?MODULE, {?MODULE, Event}, [Event, Function]).
  34. notify_reload(Event) ->
  35. gen_event:notify(?MODULE, Event).
  36. init([Event, Function]) ->
  37. {ok, #event_state{event = Event, function = Function}}.
  38. handle_call(_Request, _State) ->
  39. erlang:error(not_implemented).
  40. handle_info(_Info, _State) ->
  41. erlang:error(not_implemented).
  42. terminate(_Args, _State) ->
  43. ok.
  44. code_change(_OldVsn, State, _Extra) ->
  45. {ok, State}.
  46. handle_event({Event, Module}, State = #event_state{event = Event, function = {Mod, Fun}}) ->
  47. erlang:apply(Mod, Fun, [[Module]]),
  48. {ok, State};
  49. handle_event(_, State) -> {ok, State}.