Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: add priority filter for notify() #106

Open
hhaensel opened this issue Feb 16, 2023 · 0 comments
Open

Feature request: add priority filter for notify() #106

hhaensel opened this issue Feb 16, 2023 · 0 comments

Comments

@hhaensel
Copy link

I've often come across the need to selectively trigger handlers of observables, e.g. only trigger the first one.
In the past I've worked around that with some weired constructions, but with the introduction of priorities this could be implemented quite easily and in a very clean way.

function Base.notify(@nospecialize(observable::AbstractObservable); priority::Union{Int, Function})
    val = observable[]
    for (p, f) in Observables.listeners(observable)::Vector{Pair{Int, Any}}
        (priority isa Int ? p == priority : priority(p)) || continue
        result = Base.invokelatest(f, val)
        if result isa Consume && result.x
            # stop calling callbacks if event got consumed
            return true
        end
    end
    return false
end

Example

using Observables

o = Observable(1)

on(o) do o
    println("Called with standard priority: $o")
end

on(o, priority = -1) do r
    println("Called with priority -1: $r")
end

notify(o, priority = -1);
# Called with priority -1: 1

notify(o, priority = 0);
# Called with standard priority: 1

notify(o, priority = <(1));
# Called with standard priority: 1
# Called with priority -1: 1

What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant