GenServer State Management
GenServer With State Management
In the previous lesson, you saw how a GenServer holds simple state and handles synchronous (call) and asynchronous (cast) messages. As a quick reminder, calls wait for a reply, while casts do not. Today, you will build on that pattern to manage richer, structured state using a BankAccount server that tracks a balance and a transaction history.
Registered Name vs. PID-based GenServer APIs
In Unit 1, we used a registered name (name: __MODULE__) for our GenServer. This lets you call functions like Stack.push(1) without passing a PID, which is convenient for a single, global instance of a server.
In Unit 2, you’ll notice we switch to PID-based APIs—for example, BankAccount.deposit(account_pid, 100). This approach is necessary when you want to run multiple independent GenServer instances (such as one bank account per user), or when you use tools like the Registry for dynamic process lookup.
When to use each:
- Registered name: Use when you only need one instance of a server in your system (e.g., a single global stack or logger).
- PID-based: Use when you need many independent servers (e.g., one per user, session, or resource), or when you want to supervise and manage them dynamically.
Understanding this distinction will help you design scalable, maintainable Elixir applications!
Start the Server and Initialize Structured State
We begin by defining the module, starting the process, and initializing a map-based state that includes both balance and transactions:
Explanation:
use GenServerbrings in the GenServer behavior.start_link/1starts the process and passes the initial balance toinit/1. Note thatname: __MODULE__is not written here, which is why each call tostart_link/1returns a unique PID.init/1sets the state to a map with two keys::balanceand:transactions. This is a scalable pattern for managing multiple related fields.
Public API and State-Changing Calls
