param.reactive.reactive_ops.watch#
- reactive_ops.watch(fn=None, onlychanged=True, queued=False, precedence=0)[source]#
Add a callback to observe changes in the reactive expression’s output.
This method allows you to attach a callable function (
fn) that will be invoked whenever the output of the reactive expression changes. The callback can be either a regular or asynchronous function. If no callable is provided, the expression is eagerly evaluated whenever it updates.- Parameters:
fn (callable or coroutine function, optional) – The function to be called whenever the reactive expression changes. For function should accept a single argument, which is the new value of the reactive expression. If no function provided, the expression is simply evaluated eagerly.
- Raises:
ValueError – If
precedenceis negative, as negative precedences are reserved for internal watchers.
Examples
Attach a regular callback to print the updated value:
>>> import param >>> rx_value = param.rx(10) >>> rx_value.rx.watch(lambda v: print(f"Updated value: {v}"))
Update the reactive value to trigger the callback:
>>> rx_value.rx.value = 20 Updated value: 20
Attach an asynchronous callback:
>>> import asyncio >>> async def async_callback(value): ... await asyncio.sleep(1) ... print(f"Async updated value: {value}") >>> rx_value.rx.watch(async_callback)
Trigger the async callback:
>>> rx_value.rx.value = 30 Async updated value: 30 # Printed after a 1-second delay.