有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JavaFX InvalizationListener或ChangeListener

我只感兴趣的是房产是否发生了变化,而不是新的价值

注册InvalidationListener而不是ChangeListener是否有利

我假设对属性的更改首先会使该属性无效,并通知所有无效侦听器。仅当注册了更改侦听器,或有人请求此属性时,才会“验证”该属性/重新计算该属性,并使用新值更新所有更改侦听器

因为我对实际值不感兴趣,所以我认为只监听失效事件(属性已更改但未重新计算,某种中间状态)是一种性能优势


共 (1) 个答案

  1. # 1 楼答案

    为此,您需要实现一个ChangeListener。只有当值变得无效时,才会执行InvalidationListener。见docs

    来自ObservableValue的java文档:

    An ObservableValue generates two types of events: change events and invalidation events. A change event indicates that the value has changed. An invalidation event is generated, if the current value is not valid anymore. This distinction becomes important, if the ObservableValue supports lazy evaluation, because for a lazily evaluated value one does not know if an invalid value really has changed until it is recomputed. For this reason, generating change events requires eager evaluation while invalidation events can be generated for eager and lazy implementations.

    我添加了一个简单的例子

    public static void main(String[] args) {
    
        SimpleIntegerProperty one = new SimpleIntegerProperty(1);
        SimpleIntegerProperty two = new SimpleIntegerProperty(0);
    
        // the binding we are interested in
        NumberBinding sum = one.add(two);
        sum.addListener(observable -> System.out.println("invalidated"));
    
        // if you add a value change listener, the value will NOT be evaluated lazy anymore
        //sum.addListener((observable, oldValue, newValue) -> System.out.println("value changed from " + oldValue + " to " + newValue));
    
        // is valid, since nothing changed so far
        System.out.println("sum valid: " + sum.isValid());
        // will invalidate the sum binding
        two.set(1);
        one.set(2); // invalidation event NOT fired here!
        System.out.println("sum valid: " + sum.isValid());
        // will validate the sum binding, since it is calculated lazy when getting the value
        System.out.println("sum: " + sum.getValue());
        System.out.println("sum valid: " + sum.isValid());
    }
    

    使用InvalidationListener的问题是,如果该值再次无效,您将不会收到更改通知,因为它已经无效。你必须使用一个变更监听器

    在属性上注册更改侦听器将禁用延迟求值,因此每次触发更改侦听器时都会触发失效事件

    在我添加的样本中尝试一下