Guava EventBus多个订阅者相同的tpe

时间:2017-06-09 06:43:22

标签: guava event-bus

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class Test {

    public static class Processing { }
    public static class ProcessingResults { }
    public static class ProcessingFinished { }

    public static EventBus bus = new EventBus();

    @Subscribe
    public void receiveStartRequest(Processing evt) {
        System.out.println("Got processing request - starting processing");
    }

    @Subscribe
    public void processingStarted(Processing evt) {
        System.out.println("Processing has started");
    }

    @Subscribe
    public void resultsReceived(ProcessingResults evt) {
        System.out.println("got results");
    }

    @Subscribe
    public void processingComplete(ProcessingFinished evt) {
        System.out.println("Processing has completed");
    }


    public static void main(String[] args) {
        Test t = new Test();
        bus.register(t);
        bus.post(new Processing());
    }
}

因此,在上面的例子中,可以看到有2个订阅者接受相同类型的处理。现在,在post()时,将调用所有函数?如果将调用2个函数receiveStartRequest和processingStarted,那么它们将以何种顺序被调用?

1 个答案:

答案 0 :(得分:2)

您的方法都将被调用,并且没有预先确定的顺序。

要解决此问题,只需创建两个额外的类:ProcessingStartedProcessingRequested

public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}


public class ProcessingStarted {
  private Processing processing;
  // Constructors
  // Getters/Setters
}

然后在需要时拨打post(new ProcessingRequested(processing))post(new ProcessingStarted(processing)),而不是一个post(processing)