param.reactive.reactive_ops.when#
- reactive_ops.when(*dependencies, initial=<Undefined>) rx[source]#
Create a reactive expression that updates only when specified dependencies change.
This method creates a new reactive expression that emits the value of the current expression only when one of the provided dependencies changes. If all dependencies are of type
param.Eventand an initial value is provided, the expression will not be evaluated until the first event is triggered.- Parameters:
- Returns:
A reactive expression that updates when the specified dependencies change.
- Return type:
Examples
Use
.whento control when a reactive expression updates:>>> import param >>> from param import rx >>> from time import sleep
Define an expensive function:
>>> def expensive_function(a, b): ... print(f'multiplying {a=} and {b=}') ... sleep(1) ... return a * b
Create reactive values:
>>> a = rx(1) >>> b = rx(2)
Define a state with an event parameter:
>>> class State(param.Parameterized): ... submit = param.Event()
>>> state = State()
Create a gated reactive expression that only updates when the
submitevent is triggered:>>> gated_expr = rx(expensive_function)(a, b).rx.when(state.param.submit, initial="Initial Value") >>> gated_expr.rx.value 'Initial Value'
Trigger the update by setting the submit event:
>>> state.submit = True >>> gated_expr.rx.value multiplying a=1 and b=2 2