Observables
Observables are like Ref
s:
julia> using Observables
julia> observable = Observable(0)
Observable(0)
julia> observable[]
0
But unlike Ref
s, you can listen for changes:
julia> obs_func = on(observable) do val
println("Got an update: ", val)
end
ObserverFunction defined at none:2 operating on Observable(0)
julia> observable[] = 42
Got an update: 42
42
To remove a handler use off
with the return value of on
:
julia> off(obs_func)
true
Weak Connections
If you use on
with weak = true
, the connection will be removed when the return value of on
is garbage collected. This can make it easier to clean up connections that are not used anymore.
obs_func = on(observable, weak = true) do val
println("Got an update: ", val)
end
# as long as obs_func is reachable the connection will stay
obs_func = nothing
# now garbage collection can at any time clear the connection
Priority
One can also give the callback a priority, to enable always calling a specific callback before/after others, independent of the order of registration. So one can do:
obs = Observable(0)
on(obs; priority=-1) do x
println("Hi from first added")
end
on(obs) do x
println("Hi from second added")
end
obs[] = 2
Hi from second added
Hi from first added
Without the priority, the printing order would be the other way around. One can also return Consume(true/false)
, to consume an event and stop any later callback from getting called.
obs = Observable(0)
on(obs) do x
if x == 1
println("stop calling callbacks after me!")
return Consume(true)
else
println("Do not consume!")
end
end
on(obs) do x
println("I get called")
end
obs[] = 2
Do not consume!
I get called
obs[] = 1
stop calling callbacks after me!
The first one could of course also be written as:
on(obs) do x
return Consume(x == 1)
end
How is it different from Reactive.jl?
The main difference is Signal
s are manipulated mostly by converting one signal to another. For example, with signals, you can construct a changing UI by creating a Signal
of UI objects and rendering them as the signal changes. On the other hand, you can use an Observable both as an input and an output. You can arbitrarily attach outputs to inputs allowing structuring code in a signals-and-slots kind of pattern.
Another difference is Observables are synchronous, Signals are asynchronous. Observables may be better suited for an imperative style of programming.
API
Public
Observables.Observable
— Typeobs = Observable(val; ignore_equal_values=false)
obs = Observable{T}(val; ignore_equal_values=false)
Like a Ref
, but updates can be watched by adding a handler using on
or map
. Set ignore_equal_values=true
to not trigger an event for observable[] = new_value
if isequal(observable[], new_value)
.
Observables.ObserverFunction
— Typemutable struct ObserverFunction <: Function
Fields:
f::Function
observable::AbstractObservable
weak::Bool
ObserverFunction
is intended as the return value for on
because we can remove the created closure from obsfunc.observable
's listener vectors when ObserverFunction goes out of scope - as long as the weak
flag is set. If the weak
flag is not set, nothing happens when the ObserverFunction goes out of scope and it can be safely ignored. It can still be useful because it is easier to call off(obsfunc)
instead of off(observable, f)
to release the connection later.
Observables.async_latest
— Methodasync_latest(observable::AbstractObservable, n=1)
Returns an Observable
which drops all but the last n
updates to observable
if processing the updates takes longer than the interval between updates.
This is useful if you want to pass the updates from, say, a slider to a plotting function that takes a while to compute. The plot will directly compute the last frame skipping the intermediate ones.
Example:
observable = Observable(0)
function compute_something(x)
for i=1:10^8 rand() end # simulate something expensive
println("updated with $x")
end
o_latest = async_latest(observable, 1)
on(compute_something, o_latest) # compute something on the latest update
for i=1:5
observable[] = i
end
Observables.connect!
— Methodconnect!(o1::AbstractObservable, o2::AbstractObservable)
Forwards all updates from o2
to o1
.
See also Observables.ObservablePair
.
Observables.obsid
— Methodobsid(observable::Observable)
Gets a unique id for an observable.
Observables.off
— Methodoff(observable::AbstractObservable, f)
Removes f
from listeners of observable
.
Returns true
if f
could be removed, otherwise false
.
Observables.off
— Methodoff(obsfunc::ObserverFunction)
Remove the listener function obsfunc.f
from the listeners of obsfunc.observable
. Once obsfunc
goes out of scope, this should allow obsfunc.f
and all the values it might have closed over to be garbage collected (unless there are other references to it).
Observables.on
— Methodon(f, observable::AbstractObservable; weak = false, priority=0, update=false)::ObserverFunction
Adds function f
as listener to observable
. Whenever observable
's value is set via observable[] = val
, f
is called with val
.
Returns an ObserverFunction
that wraps f
and observable
and allows to disconnect easily by calling off(observerfunction)
instead of off(f, observable)
. If instead you want to compute a new Observable
from an old one, use map(f, ::Observable)
.
If weak = true
is set, the new connection will be removed as soon as the returned ObserverFunction
is not referenced anywhere and is garbage collected. This is useful if some parent object makes connections to outside observables and stores the resulting ObserverFunction
instances. Then, once that parent object is garbage collected, the weak observable connections are removed automatically.
Example
julia> obs = Observable(0)
Observable(0)
julia> on(obs) do val
println("current value is ", val)
end
ObserverFunction defined at REPL[17]:2 operating on Observable(0)
julia> obs[] = 5;
current value is 5
One can also give the callback a priority, to enable always calling a specific callback before/after others, independent of the order of registration. The callback with the highest priority gets called first, the default is zero, and the whole range of Int can be used. So one can do:
julia> obs = Observable(0)
julia> on(obs; priority=-1) do x
println("Hi from first added")
end
julia> on(obs) do x
println("Hi from second added")
end
julia> obs[] = 2
Hi from second added
Hi from first added
If you set update=true
, on will call f(obs[]) immediately:
julia> on(Observable(1); update=true) do x
println("hi")
end
hi
Observables.onany
— Methodonany(f, args...; weak::Bool = false, priority::Int = 0, update::Bool = false)
Calls f
on updates to any observable refs in args
. args
may contain any number of Observable
objects. f
will be passed the values contained in the refs as the respective argument. All other objects in args
are passed as-is.
See also: on
.
Observables.throttle
— Methodthrottle(dt, input::AbstractObservable)
Throttle a signal to update at most once every dt
seconds. The throttled signal holds the last update of the input
signal during each dt
second time window.
Extensions of Base methods or internal methods
Observables.ObservablePair
— TypeObservablePair(first, second)
Two observables trigger each other, but only in one direction as otherwise there will be an infinite loop of updates
Base.getindex
— Methodobservable[]
Returns the current value of observable
.
Base.map!
— Methodmap!(f, result::AbstractObservable, args...; update::Bool=true)
Updates result
with the result of calling f
with values extracted from args. args
may contain any number of Observable
objects. f
will be passed the values contained in the refs as the respective argument. All other objects in args
are passed as-is.
By default result
gets updated immediately, but this can be suppressed by specifying update=false
.
Example
We'll create an observable that can hold an arbitrary number:
julia> obs = Observable{Number}(3)
Observable{Number}(3)
Now,
julia> obsrt1 = map(sqrt, obs)
Observable(1.7320508075688772)
creates an Observable{Float64}
, which will fail to update if we set obs[] = 3+4im
. However,
julia> obsrt2 = map!(sqrt, Observable{Number}(), obs)
Observable{Number}(1.7320508075688772)
can handle any number type for which sqrt
is defined.
Base.map
— Methodobs = map(f, arg1::AbstractObservable, args...; ignore_equal_values=false)
Creates a new observable obs
which contains the result of f
applied to values extracted from arg1
and args
(i.e., f(arg1[], ...)
. arg1
must be an observable for dispatch reasons. args
may contain any number of Observable
objects. f
will be passed the values contained in the observables as the respective argument. All other objects in args
are passed as-is.
If you don't need the value of obs
, and just want to run f
whenever the arguments update, use on
or onany
instead.
Example
julia> obs = Observable([1,2,3]);
julia> map(length, obs)
Observable(3)
Base.notify
— Methodnotify(observable::AbstractObservable)
Update all listeners of observable
. Returns true if an event got consumed before notifying every listener.
Base.setindex!
— Methodobservable[] = val
Updates the value of an Observable
to val
and call its listeners.
Observables.clear
— Methodclear(obs::Observable)
Empties all listeners and clears all inputs, removing the observable from all interactions with it's parent.
Observables.to_value
— Methodto_value(x::Union{Any, AbstractObservable})
Extracts the value of an observable, and returns the object if it's not an observable!
Observables.@map!
— Macro@map!(d, expr)
Wrap AbstractObservables
in &
to compute expression expr
using their value: the expression will be computed every time the AbstractObservables
are updated and d
will be set to match that value.
Examples
julia> a = Observable(2);
julia> b = Observable(3);
julia> c = Observable(10);
julia> Observables.@map! c &a + &b;
julia> c[]
10
julia> a[] = 100
100
julia> c[]
103
Observables.@map
— Macro@map(expr)
Wrap AbstractObservables
in &
to compute expression expr
using their value. The expression will be computed when @map
is called and every time the AbstractObservables
are updated.
Examples
julia> a = Observable(2);
julia> b = Observable(3);
julia> c = Observables.@map &a + &b;
julia> c[]
5
julia> a[] = 100
100
julia> c[]
103
Observables.@on
— Macro@on(expr)
Wrap AbstractObservables
in &
to execute expression expr
using their value. The expression will be computed every time the AbstractObservables
are updated.
Examples
julia> a = Observable(2);
julia> b = Observable(3);
julia> Observables.@on println("The sum of a+b is $(&a + &b)");
julia> a[] = 100;
The sum of a+b is 103