Skip to content

Commit 5aacdec

Browse files
committed
iluwatar#590 add explanation for Callback
1 parent eeea3c7 commit 5aacdec

File tree

3 files changed

+59
-52
lines changed

3 files changed

+59
-52
lines changed

callback/README.md

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,64 @@ tags:
99
---
1010

1111
## Intent
12-
Callback is a piece of executable code that is passed as an
13-
argument to other code, which is expected to call back (execute) the argument
14-
at some convenient time.
12+
Callback is a piece of executable code that is passed as an argument to other code, which is expected to call back
13+
(execute) the argument at some convenient time.
14+
15+
## Explanation
16+
17+
Real world example
18+
19+
> We need to be notified after executing task has finished. We pass a callback method for the executor and wait for it to call back on us.
20+
21+
In plain words
22+
23+
> Callback is a method passed to the executor which will be called at defined moment.
24+
25+
Wikipedia says
26+
27+
> In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time.
28+
29+
**Programmatic Example**
30+
31+
Callback is a simple interface with single method.
32+
33+
```java
34+
public interface Callback {
35+
36+
void call();
37+
}
38+
```
39+
40+
Next we define a task that will execute the callback after the task execution has finished.
41+
42+
```java
43+
public abstract class Task {
44+
45+
final void executeWith(Callback callback) {
46+
execute();
47+
Optional.ofNullable(callback).ifPresent(Callback::call);
48+
}
49+
50+
public abstract void execute();
51+
}
52+
53+
public final class SimpleTask extends Task {
54+
55+
private static final Logger LOGGER = getLogger(SimpleTask.class);
56+
57+
@Override
58+
public void execute() {
59+
LOGGER.info("Perform some important activity and after call the callback method.");
60+
}
61+
}
62+
```
63+
64+
Finally here's how we execute a task and receive a callback when it's finished.
65+
66+
```java
67+
var task = new SimpleTask();
68+
task.executeWith(() -> LOGGER.info("I'm done now."));
69+
```
1570

1671
## Class diagram
1772
![alt text](./etc/callback.png "Callback")

callback/src/main/java/com/iluwatar/callback/LambdasApp.java

Lines changed: 0 additions & 48 deletions
This file was deleted.

callback/src/main/java/com/iluwatar/callback/Task.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public abstract class Task {
3333
/**
3434
* Execute with callback.
3535
*/
36-
final void executeWith(final Callback callback) {
36+
final void executeWith(Callback callback) {
3737
execute();
3838
Optional.ofNullable(callback).ifPresent(Callback::call);
3939
}

0 commit comments

Comments
 (0)