Getting values inside foreach to outside

I am trying to do as below
1- Get chatrooms name from mnesia databse as list,
2- Run each chatroom with Pid using for each loop,
3- Store each chatroom name and its pid into orddict as a state of the server process.

below is what I am trying:

     initialize_rooms ->
     RoomsList = lists:delete(schema,mnesia:system_info(tables)),  
     io:format("Retrived rooms from mnesia :  ~p ~n", [RoomsList]),


   lists:foreach(fun(Roomname) ->

       RoomPid = chatapp_chatroom:start_link(Roomname),
       io:format("Room ~p has been initilized ~n", [Roomname]),
       UpdatedRooms = orddict:store(Roomname, RoomPid, S#state.rooms),
       S#state{rooms= UpdatedRooms} 
       end, RoomsList),
   loop(S);

and the loop state is assigned as

loop(S=#state{}) →

The chatrooms created well, unless the state of the process loop(S) doesn’t updated, it keeps return S as blank orddict. i.e., it doesn’t get any value from inside the foreach loop. What I am doing wrong please ?

Erlang is immutable, and there is no variable re-assignment. To achieve what you want, you can use a reduction (lists:foldr in the stdlib), then update the state with the result. Here is a quick untested example:

Rooms = S#state.rooms,
RoomsNew =
  lists:foldr(fun(Roomname, RoomsAcc) ->
       RoomPid = chatapp_chatroom:start_link(Roomname),
       io:format("Room ~p has been initilized ~n", [Roomname]),
       orddict:store(Roomname, RoomPid, RoomsAcc)
   end, Rooms, RoomsList),
StateNew = S#state{rooms = RoomsNew},
loop(StateNew);
1 Like

Works like charm! many thanks