gpt4 book ai didi

Guava EventBus 多个订阅者相同的 tpe

转载 作者:行者123 更新时间:2023-12-03 09:08:56 27 4
gpt4 key购买 nike

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() 时,哪些函数将被调用?如果将调用 receiveStartRequest 和processingStarted 这两个函数,那么它们将按什么顺序被调用?

最佳答案

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

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

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


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

然后在需要时调用 post(newProcessingRequested(processing))post(newProcessingStarted(processing)),而不是单个 post(processing) .

关于Guava EventBus 多个订阅者相同的 tpe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44451025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com