Reputation: 9360
I am currently reading LYAE
and i am trying to understand why must gen_fsm
state methods have to return anything at all according to the source
{reply, Reply, NextStateName, NewStateData}
{reply, Reply, NextStateName, NewStateData, Timeout}
{reply, Reply, NextStateName, NewStateData, hibernate}
{next_state, NextStateName, NewStateData}
{next_state, NextStateName, NewStateData, Timeout}
{next_state, NextStateName, NewStateData, hibernate}
{stop, Reason, Reply, NewStateData}
{stop, Reason, NewStateData}
Can someone explain to me if i have 3 state methods : a
,b
and c
and the state machine would be defined as follows:
a()->
receive
something -> b();
_ -> error(err)
end.
b()->
receive
somethingelse-> c();
_ ->
end.
Why would i ever need the return result of the next state method?
someMethod()->
receive
_ ->
{next_state, NextStateName, NewStateData}=someNextMethod(),
//why would i place code here? What could i possibly do with the above tuple ?
end.
I do not understand why would i put code AFTER the call to the next state method ? All calls are recursive so besides the initial state where i could actually do something after the fsm ended or threw , why would i put code in the other states?
Upvotes: 2
Views: 98
Reputation: 48599
{next_state, NextStateName, NewStateData}=someNextMethod(),
//why would i place code here? What could i possibly do with the above tuple ?
For instance:
{next_state, NextStateName, NewStateData}=someNextMethod(),
{next_state, NextStateName, NewStateData + 1}
Or:
{next_state, NextStateName, NewStateData}=someNextMethod(),
ModifiedStateData = do_calculation(NewStateData),
{next_state, NextStateName, ModifiedStateData}
Upvotes: 2
Reputation: 14042
You are correct, there is no need of return value, and you must have a recursive call to some function which will wait on a receive statement: it is necessary to make things evolve (because of immutability of variable) and to react to a new message.
The point is that your example is a one module state machine, while when you use a gen_fsm behavior, there are, at least 2 modules at play:
Each module have very different roles.
In short, the gen_fsm is a simple recursive loop waiting for "event" messages which maintain, at least, the State_name variable. It uses helper functions stored in the callback module to describe its behavior. Not so far from what you say, but with the constraints brought by a generic module - and also the advantages of an integrated to OTP and well validated code.
Upvotes: 3