Create a callback handler to handle multiple callbacks in Android

I have an Android app that interacts with third-party equipment through the library provided by the vendor. When the data from the equipment is ready for processing, the library turns to my application.

A third-party library, thanks to it, only makes one callback for the application. However, my application has several different asynchronous tasks that it would like to do when callback is called (for example, logging, updating the user interface display, calling external programs). Trying to deploy an event, in a sense, in a variety of ways. So, I'm going to do this in my Application class:

interface MyCallback { public void doSomething(ArrayList<DataClass>); } public class MyApp extends Application { ... private MyCallback cb; public void registerCallback (MyCallback callback) { cb = callback; } public methodCalledBy3rdPartyAPIOnData (ArrayList<DataClass> data){ cb.doSomething(ArrayList<DataClass> data); } 

which will work for one method to call, but I had a problem with how to do this for a series of callbacks ... and make sure they are called asynchronously. Are there any examples or best practices for this kind of thing in an Android application or in general in Java?

+6
source share
1 answer

I would use a slightly adapted observer pattern (adaptation notifies each observer in a new thread):

Your callback handler is subject (i.e. enforced):

 public class Subject { private List<Observer> observers = new ArrayList<>(); public void registerObserver(Observer observer) { observers.add(observer); } public void notifyObservers(Object data) { for (final Observer observer : observers) { new Thread(new Runnable() { @override public void run() { observer.notify(data); } }).start(); } } public methodCalledBy3rdPartyAPIOnData (ArrayList<DataClass> data){ notifyObservers((Object)data); } } 

And each of the real handlers must implement the following interface

 public interface Observer { public void notify(Object data); } 

And register yourself by calling subject.registerObserver(this) .

+8
source

Source: https://habr.com/ru/post/945425/


All Articles