return from Async BukkitRunnable

Discussion in 'Plugin Development' started by Symphonic, Dec 21, 2019.

Thread Status:
Not open for further replies.
  1. Offline

    Symphonic

    Essentially I want to run an Async task that will return a number and then get that in the main code... how?
     
  2. Offline

    KarimAKL

    @Symphonic You can't change the return type of a method when overriding it. Instead you'd do something like this:
    Code:Java
    1. private int number = 0;
    2.  
    3. public int getNumber() {
    4. return number;
    5. }
    6.  
    7. // Some place in your code
    8. new BukkitRunnable() {
    9. @Override
    10. public void run() {
    11. number = someValue;
    12. }
    13. }
     
  3. Offline

    robertlit

    I don't think that's what they mean, note they said async

    You can't return a value from another thread as it will require holding the main thread and thus making it useless to run async. Instead you can use callbacks, here is an example using the Consumer interface.
    The method to get the data (use where you access your database/file/whatever):
    Code:
    public void getPlayerKills(String name, Consumer<Integer> consumer) {
        new BukkitRunnable() {
            @Override
            public void run() {
                int kills = ... // Get data from your database/file about the player
                new BukkitRunnable() {
                     @Override
                     public void run() {
                        consumer.accept(kills);
                     }
                 }.runTask(plugin)
            }
        }.runTaskAsychronously(plugin);
    }
    
    Let's say there is a command that will retrieve how many kills each player has, here is how it's going to look, using the method from before:
    Code:
    //Inside the on command method
    String playerName = args[0];
    plugin.getDatabase()/*returns the class that has the method from the previous code block*/.getPlayerKills(playerName, kills -> sender.sendMessage(kills));
    Hope this helps :)
     
    Last edited: Dec 22, 2019
  4. Offline

    Symphonic

    omg forgot to mark this as solved, I figured out about callbacks a few days ago but thanks a lot anyways!
     
Thread Status:
Not open for further replies.

Share This Page