Repetitive Consumer For Loop

百般思念 提交于 2021-02-11 12:33:44

问题


I am using a library with a method where I call a method that takes an event class and a consumer to call when the event fires. This method returns a void. I need to call the method again in the consumer then in that consumer call it again etc. (a lot of times). How can I put this in a for loop to avoid typing out this method loads of times? Code:

ShurikenBot.getInstance().getEventWaiter().waitForEvent(MessageReactionAddEvent.class,
                    t -> t.getMessageId().equals(m.getId()) && event.getAuthor().getId().equals(t.getMember().getUser().getId())
                            && t.getReaction().getReactionEmote().getName().equals("\u25B6"),
                    t ->
                            t.getChannel().getMessageById(t.getMessageId()).queue(msg -> {
                                System.out.println("yes");
                                // i want to call waitForEvent() again here
                                msg.editMessage(builder.setTitle("Shuriken Tutorial - Step 2").setImage("https://i.615283.net/u/47794c.jpg").build()).queue();
                                t.getReaction().removeReaction(t.getUser()).queue();
                            }));

回答1:


Instead of using the EventWaiter you could create a State-Machine using a generic event listener.

public StateMachine extends ListenerAdapter {
    private final long messageId;
    private final long userId;
    private final String emoji;

    private int state = 0;

    public StateMachine(...) {...}

    @Override
    public void onMessageReactionAdd(MessageReactionAddEvent event) {
        if (event.getMessageIdLong() != messageId) return;
        if (event.getUser().getIdLong() != userId) return;
        if (!event.getReactionEmote().getName().equals(emoji)) return;
        switch (state) {
        case 0:
            System.out.println("yes");
            event.getChannel().editMessageById(messageId, ...).queue();
            event.getReaction().removeReaction(event.getUser()).queue();
            state = 1;
            break;
        case 1:
            System.out.println("This is the next awaited event");
            // do something here...
            break;
        }
    }
}

Then you can define a final state in which you remove the event listener again.



来源:https://stackoverflow.com/questions/56692854/repetitive-consumer-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!