Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
For what?
Let's say you came to a medical institution for a certificate on some specialist there, and for example, the certificate will be made for 4 hours. Eventually, you will be able to pick it up at the registration desk.
You have two strategies:
1. Every 5 min. approach the reception "Is the certificate for Pupkin's name ready?"
2. Leave a business card with a phone number for Pupkin and ask him to call when the certificate is ready.
Which strategy is more convenient? ;)
This is the principle "Don't call us, we'll call you ourselves".
So in programming there is a certain code that will be called when certain conditions occur (the network is available, the file has appeared, the button has been pressed, the program is shutting down, etc.)
The code that is called is callback - "Callback".
In the example above, the callback is Pupkin, and the event is "help is ready".
Simple example
public interface InitCallback {
void init();
class Http implements InitCallback {
void sendData(String url, SuccessCallback success, FailureCallback fail) {
try {
//Делаем реквест
String httpResult = "200";
//Вызываекм коллбек
success.success(httpResult);
} catch (Exception ex) {
//Вызываекм коллбек в случае ошибки
fail.fail("400");
}
}
public void init() {
System.out.println("Вызван init коллбек");
}
interface SuccessCallback {
void success(String result);
}
interface FailureCallback {
void fail(String error);
}
public static void main(String[] args) {
Http http = new Http();
if (http instanceof InitCallback) {
//Если это наш интерфес, то вызываем колбек
http.init();
}
http.sendData("/my/api", new SuccessCallback() {
@Override
public void success(String result) {
System.out.println("Успешный колбек: " + result);
}
}, new FailureCallback() {
@Override
public void fail(String error) {
System.out.println("Колбек вернул ошибку: " + error);
}
});
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question