How do I make use of gen_statem(enterstate, L

Hi,

I am building finite state machines and would like to enter a state function directly when transition is made to the state.

In the documentation I found:

‘StateName’(enter, OldStateName :: state_name(), data())

When I make such a state function for a state, it never enters that state function. Only signal driven state functions are called.

BTW, I use:

callback_mode() ->
    state_functions.

I can’t really find out more information on this (or am I just blind?). What is the purpose of this mechanism and how do I use it?

Cheers, Erik

Try

callback_mode() ->
    [state_functions, state_enter].

It is described in https://www.erlang.org/doc/apps/stdlib/gen_statem.html#t:state_enter/0

Svilen

Here’s a working example:

-module(foo_fsm).

-behaviour(gen_statem).

-export([init/1, handle_event/4, callback_mode/0,
        terminate/3, code_change/4]).
-export([null/3]).

callback_mode() ->
    [state_functions, state_enter].

init(_Args) ->
    process_flag(trap_exit, true),
    {ok, null, []}.

null(enter, OldStateName, Data) ->
    io:fwrite("~w:~w(~w, ~w, ~w)~n",
            [?MODULE, ?FUNCTION_NAME, enter, OldStateName, Data]),
    keep_state_and_data;
null(EventType, EventContent, Data) ->
    io:fwrite("~w:~w(~w, ~w, ~w)~n",
            [?MODULE, ?FUNCTION_NAME, EventType, EventContent, Data]),
    keep_state_and_data.

handle_event(_EventType, _EventContent, _State, _Data) ->
    keep_state_and_data.

terminate(_Reason, _State, _Data) ->
    ok.

code_change(_OldVsn, OldState, OldData, _Extra) ->
    {ok, OldState, OldData}.

This will print the called callback functions and arguments:

1> {ok, Pid} = gen_statem:start(foo_fsm, [], []).
foo_fsm:null(enter, null, [])
{ok,<0.86.0>}
2> gen_statem:cast(Pid, bar).
foo_fsm:null(cast, bar, [])
ok

It was really so simple… And it works like a charm now!

Thanks! :grinning_face: