[JAVA] Try to make a simple callback

〇Overview

As the architecture of Android apps becomes more complex, the classes that perform asynchronous information and the classes that use it are separated. In that case, you have to tell another class when you get the data obtained asynchronously, but it is quite troublesome. So, there are various libraries such as AsyncTaskLoader, which is a support library, and libraries that handle event buses (EventBus, RxJava, etc.), but I didn't have much information on how to make primitive callbacks using the interface, so I summarized them. ..

〇 Sample source

GitHub

〇 Class list

MainActivity ・ Main class -Create an instance of TasksRepository and TasksBackgroundDataSource. -View display functions are also included here for simplicity.

TasksRepository -A class that holds and operates data. -The instance of TasksBackgroundDataSource is acquired at the time of generation. -Throw a data acquisition request to TasksBackgroundDataSource, or receive a callback and throw a display request to MainActivity.

TasksBackgroundDataSource -A class that brings data asynchronously. -The TasksDataSource interface is implemented. ・ (Since writing the process of bringing data from the network makes the process complicated, just set up a separate thread and embed the data)

TasksDataSource -An interface that summarizes the processing relationships of data acquisition.

Task -A data class that manages the acquired values.

〇Excerpt from the callback part

(Note) Listed in the reverse order of the above class list for easy understanding.

Define a function to retrieve data and a function called a callback

TasksDataSource


public interface TasksDataSource {

    //Function called as a callback
    interface LoadTasksCallback {
        void onTasksLoaded(List<Task> tasks);
        void onDataNotAvailable();
    }

    //Data acquisition function (It is not necessary to write it separately, but write it all together)
    void getTasks(@NonNull LoadTasksCallback callback);
}

Implemented data acquisition function getTasks After getting it, I will call the callback function

TasksBackgroundDataSource


public class TasksBackgroundDataSource implements TasksDataSource {

    @Override
    public void getTasks(@NonNull final LoadTasksCallback callback) {

        final Handler handler = new Handler();

        //Thread launch
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                 //Request processing from the main thread using Handler (for View update)
                 handler.post(new Runnable() {
                     @Override
                     public void run() {

                         //Data acquisition
                         //・
                         //・

                         if (tasks.isEmpty()) {
                             //Processing when there is no data
                             callback.onDataNotAvailable();

                         } else {
                             //Processing when there is data
                             callback.onTasksLoaded(tasks);
                         }
                     }
                 });

            }
        });
        thread.start();
    }
}

Call getTask of TasksBackgroundDataSource, create an instance of LoadTasksCallback as an argument, implement the function you want to call and pass it.

TasksRepository


        mTasksBackgroundSource.getTasks(new TasksDataSource.LoadTasksCallback() {
            //Processing called after data acquisition (when there is data)
            @Override
            public void onTasksLoaded(List<Task> tasks) {
                MainActivity.showTextMsg(changeTasksToString(tasks));
            }
            //Processing called after data acquisition (when there is no data)
            @Override
            public void onDataNotAvailable() {
                Log.w("DEBUG_DATA","TaskRepository onDataNotAvailable");
            }
        });

〇Summary

After all, call this! I'm just throwing an instance that implements the process in the data acquisition function, but the design to realize it is complicated. This is based on Google's MVP sample, but there The presenter called the getTask of the Repository, and when the getTask of the DataSource was called, the callback was called in a string. As the number of acquisition destinations increases, it becomes difficult to understand, so after all it is better to use the library. I tried to summarize the basics for the time being.

〇Reference

android/architecture-samples

Recommended Posts

Try to make a simple callback
Try to make a peepable iterator
[Beginner] Try to make a simple RPG game with Java ①
Try to make a music player using Basic Player
Make a language! (Making a simple calculator ②)
How to make a Java container
How to make a JDBC driver
A simple sample callback in Java
Make a language! (Making a simple calculator ①)
How to make a splash screen
How to make a Jenkins plugin
How to make a Maven project
Try to create a server-client app
CompletableFuture Getting Started 2 (Try to make CompletableFuture)
How to make a Java array
Try to make a cross-platform application with JRuby (jar file generation)
Try to make a CS 3D tile from the Geographical Survey tile
Interface Try to make Java problem TypeScript 7-3
How to make a Java calendar Summary
How to make a Discord bot (Java)
[docker] [nginx] Make a simple ALB with nginx
Java beginner tried to make a simple web application using Spring Boot
Make a margin to the left of the TextField
java I tried to break a simple block
I did Java to make (a == 1 && a == 2 && a == 3) always true
Try to create a bulletin board in Java
Increment behavior Try to make Java problem TypeScript 3-4
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
String operation Try to make Java problem TypeScript 9-3
How to make a lightweight JRE for distribution
How to make a follow function in Rails
I tried to make a simple game with Javafx ① "Let's find happiness game" (unfinished)
Try to make a timeline report of method execution time using JFR API
How to make a factory with a model with polymorphic association
Try to release gem
Initialization of for Try to make Java problem TypeScript 5-4
I tried to decorate the simple calendar a little
How to make JavaScript work on a specific page
[Personal memo] Make a simple deep copy in Java
Try to make an addition program in several languages
Let's make a robot! "A simple demo of Java AWT Robot"
I tried to make a login function in Java
How to make shaded-jar
Make a reflection utility ②
Make a reflection utility ③
Try to solve a restricted FizzBuzz problem in Java
How to make a cache without thinking too much
Make a reflection utility ①
How to make a mod for Slay the Spire
Try to build a Java development environment using Docker
Try sending a notification.
[Introduction to Android application development] Let's make a counter
A memo to check when you try to use Lombok
[JavaFX] Try to make a software MIDI keyboard Part 2 Slide your finger to change the scale
How to deploy a simple Java Servlet app on Heroku
I want to make a specific model of ActiveRecord ReadOnly
I want to make a list with kotlin and java!
I just wanted to make a Reactive Property in Java
I want to make a function with kotlin and java!
Make a simple CRUD with SpringBoot + JPA + Thymeleaf ① ~ Hello World ~
Learning Ruby with AtCoder 13 How to make a two-dimensional array