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.Event and an initial value is provided, the expression will not be evaluated until the first event is triggered.

Parameters:
  • dependencies (Parameter or reactive expression rx) – Dependencies that trigger an update in the reactive expression.

  • initial (object, optional) – A placeholder value that is used until a dependency event is triggered. Defaults to Undefined.

Returns:

A reactive expression that updates when the specified dependencies change.

Return type:

rx

Examples

Use .when to 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 submit event 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