Java callback method details

Callback is defined in Wikipedia as:

In computer programming, callback function refers to the reference of an executable code passed to other code through function parameters.

Its purpose is to allow the underlying code to call subroutines defined at a high level.

For example, it may be clearer: take the network request with retrofit in android as an example. This is an example of asynchronous callback.

After initiating the network request, the app can continue to do other things. The results of the network request are generally returned through onresponse and onfailure. Take a look at the code of the relevant part:

Ignore the generics in the callback above. According to the definition in Wikipedia, all the code in the anonymous inner class can be regarded as the reference of a piece of executable code passed from function parameters to other codes. Onresponse and onfailure are callback methods. The bottom code is the unchanged network request, and the subroutine defined at the top is the callback. Because the specific implementation is handed over to the user, it has high flexibility. The above is associated through the enqueue (callback) method.

Steps for callback methods

The callback mentioned above is a very general concept. Put it on the program writing, you can say:

Class a calls a method C in the B class, and then in the B class calls D in class A, in which D is the callback method. Class B is the low-level code, and class A is the high-level code.

Therefore, through the above explanation, we can infer some things. In order to represent the universality of D method, we use the form of interface to make d method called an interface method. If class B wants to call method D in class A, class A is bound to implement this interface. In this way, there will be polymorphism according to different implementations, making the method flexible.

If class a wants to call a method C in class B, it must contain a reference to B, otherwise it cannot be called. This step is called registering the callback interface. So how to call method D in class A in class B in turn? Directly through the above method C, method C in class B accepts an interface type parameter, so you only need to call method d with this interface type parameter in method C, and then you can call method D in class A in class B in reverse. This step is called calling callback interface.

This means that in the C method of class B, you need to call the D method of class A in turn, which is a callback. A calls B directly, which can be regarded as high-level code and use the underlying API. We often write programs like this. B calls a as a callback, and the underlying API needs high-level code to execute.

Finally, summarize the steps of callback method:

Example of callback

We take a son playing a game and waiting for his mother to tell his son to eat when he has finished the meal as an example, and write the callback according to the above steps;

In the above example, it is obvious that the callback interface should be implemented by the son and called by the mother. So we first define a callback interface, and then let our son implement the callback interface.

Its code is as follows:

Then we need to define a mother class with a method docook containing interface parameters

We pass a test class:

This example is a typical callback example. The Son class implements the callback method of the interface, and calls the doCook in the Mom class through the askMom method to implement the registration callback interface, which is equivalent to the code C calling class B in class a. Docook in mom class calls back eat in son class to tell the result in son class.

In this way, we have implemented a simple and well-defined callback.

Further exploration of callback examples

Let's mainly look at the code of son class:

In addition to outputting some statements, the really useful part of this class is mom Docook (son. This) and rewrite the eat method. Therefore, we can abbreviate this callback in the form of anonymous inner class. Its code is as follows:

Cancel the son class and directly implement the eat method in the main method through the anonymous inner class. In fact, the anonymous inner class is the embodiment of callback.

Asynchronous callback and synchronous callback

Callback as mentioned above, a calls method C in class B, and then calls method D in class a through class a objects in method C.

Let's talk about asynchrony and synchronization. Let's talk about the concept of synchronization first

synchronization

Synchronization means that when a method is called, if the previous method call is not completed, a new method call cannot be made. In other words, things must be done one by one, and the next can only be done after the previous one is completed.

asynchronous

Compared with synchronization, asynchrony can call a new method without waiting for the end of the previous method call. Therefore, in asynchronous method calls, a method is needed to notify the user of the method call result.

How to implement asynchrony

The most common way to implement asynchrony in Java is to let the methods you want to asynchronously execute in a new thread.

We will find that in asynchronous method calls, a method is required to notify the user of the call result. Combined with the above, we will find that the callback method is suitable for doing this, and notify the user of the call result through the callback method.

The asynchronous callback is that when a calls method C of B, it is done in a new thread.

The above example of a mother notifying her son to eat is an example of an asynchronous callback. In a new thread, call the doCook method, and finally accept the return value through eat. Of course, after using lamdba, the essence is the same.

Synchronous callback is that a calls B's method C without a new thread. When executing this method C, we can't do anything but wait for it to complete.

Examples of synchronous and asynchronous callbacks

Let's look at an example of a synchronous callback in Android:

Button registers the callback function through setonclicklistener. As written above, it passes in the reference of the interface in the form of anonymous inner class. Since the button call setonclicklistener does not create a new thread, this is a synchronous callback.

Asynchronous callback is the example we talked about at the beginning:

The enqueue method is an asynchronous method to request remote network data. Its internal implementation is executed through a new thread.

Through these two examples, we can see that the use of synchronous callback and asynchronous callback is actually designed according to different requirements. One cannot replace the other. For example, in the above button click event, if it is an asynchronous callback, the click effect does not appear immediately after the user clicks the button, and the user will not perform other operations, it will feel very strange. As for the asynchronous callback of network request, because the user is not clear about the method execution due to the possible absence of request resources, unstable network connection and other reasons, the asynchronous callback will be used to do other things after initiating the method call, and then wait for the callback notification.

Application of callback method in communication

Except for the callback of the network request framework, the callback methods mentioned above have no parameters. Next, let's take a look at adding parameters to the callback methods to realize some communication problems.

If we want class A to get the data of class B after a series of calculations and processing, and the two classes can't get the data by simply referencing B to class A. We can consider callback.

The steps are as follows:

The above steps are a little abstract. Let's take a look at an example. One is the client and the other is the server. The client requests the time-consuming data processed by the server.

Next, let's take a look at the test example:

The results are as follows:

The above is to communicate through callback.

The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. At the same time, I also hope to support a lot of programming tips!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>