Created
September 17, 2018 10:20
-
-
Save prameshbhattarai/9da85b5fed00a7236b48f5c8fdc34c12 to your computer and use it in GitHub Desktop.
example of calling async callback function in java --fun--
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.callback.fun; | |
import java.util.function.Consumer; | |
public class Callback { | |
private static final double salary = 75_000; | |
private static void getSalary(Consumer<Double> callback) { | |
System.out.println("get salary invoked"); | |
new Thread(() -> { | |
Async.task(1000); | |
callback.accept(Callback.salary); | |
}).start(); | |
} | |
private static void subtractTax(double salary, Consumer<Double> callback) { | |
System.out.println("subtract tax invoked"); | |
new Thread(() -> { | |
Async.task(1000); | |
callback.accept(salary * 0.75); | |
}).start(); | |
} | |
private static void subtractRent(double afterTaxSalary, Consumer<Double> callback) { | |
System.out.println("subtract rent invoked"); | |
new Thread(() -> { | |
Async.task(1000); | |
callback.accept(afterTaxSalary - 20_000); | |
}).start(); | |
} | |
private static void getDisposableIncome(Consumer<Double> callback) { | |
System.out.println("get disposable income invoked"); | |
new Thread(() -> { | |
Async.task(1000); | |
getSalary((totalSalary) -> { | |
subtractTax(totalSalary, (afterTaxSalary) -> { | |
subtractRent(afterTaxSalary, callback::accept); | |
}); | |
}); | |
}).start(); | |
} | |
public static void main(String... args) { | |
Callback.getDisposableIncome((disposableIncome) -> { | |
System.out.println("Our final disposable income is " + disposableIncome); | |
}); | |
} | |
private static class Async { | |
static void task(int milliSeconds) { | |
try { | |
Thread.sleep(milliSeconds); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment