What is a ReactiveModel and how to use it
mainA ReactiveModel is a class that groups related reactive state and behavior into a single unit. Each instance of a ReactiveModel owns its own independent graph of writable fields, computed values, linked state, effects, and resources.
Use ReactiveModel to represent application concepts like forms, stores, view models, workflows, or services.
Note on Naming Convention:
When defining new models, use the lowercase primitive API: field(...), @computed, @linked, @effect, and @resource. Avoid using the uppercase class names (like Signal or Effect) in your model definitions.
from reaktiv import ReactiveModel, computed, effect, field
class ShoppingCart(ReactiveModel):
unit_price = field(12.50)
quantity = field(1)
discount = field(0.0)
@computed
def subtotal(self) -> float:
return self.unit_price() * self.quantity()
@computed
def total(self) -> float:
return self.subtotal() * (1 - self.discount())
@effect
def show_total(self) -> None:
print(f"{self.quantity()} item(s): ${self.total():.2f}")
cart = ShoppingCart()
cart.quantity.set(3)
cart.dispose()