Android: How to communicate between non-ui threads and process data on the caller thread?

Problem:

I need to pass an indicator \ object to thread B from thread A, and this indication needs to be processed on thread A asynchronously (without blocking).

Background:

I have developed an SDK (thread B) that basically starts some tasks with the ThreadPoolExecutor mechanism. 3rd party application (thread A) that uses SDK requests to start task and impl. result callback, tasks can run in parallel and return the result asynchronously.

i.e. fragment of request:

SDK.taskA(new CustomCallback() {
    @Override
    public void onFinish(String s) {
         // run some code - let refer to as **Section A**
    }
});

      

ie SDK returns callback:

mCustomCallback.onFinish(String s);

      

The problem is that the callback - "onFinish" is being executed on the worker thread - the SDK (obviously) and not on the caller thread. that is, if the call flow id (A) is 400 and worker (B) is 500, I need thread 400 to call "onFinish".

I tried another solution, but it didn't match my requirements:

  • Handlers - A handler seems to be the obvious solution, but for managing and observing that Looper.prepare will only be called once per thread, it's tricky, what if a third party application has already defined a handler for the calling thread in its application for its own purposes? or what if it starts many different SDK tasks from one thread? this requires starting processing the Looper state for each flow check if it exists or not.

  • LocalBrodcastReceivers - Returns indication to UI only

  • Callback - transfer interface, indication of return to worker thread (B).

  • Shared Memory - Requires the caller thread (A) to be blocked until an indication is received from the worker thread (B)

    • Pipes - Requires the caller thread (A) to be blocked until a pointer is received from the worker thread (B)

The purpose of this construct is that I cannot predict the amount of work that a third party application will preform on a callback from the SDK, so I don't want this to happen to one of my thread pool workers.

Also, I am specifically talking about 2 non-ui threads due to the ui thread being one of them, there are many good solutions out there.

Any thoughts?

+3


source to share


1 answer


You can use otto , your event bus, designed to decouple different parts of your application, allowing them to communicate effectively.



You can send your data from one thread and you can subscribe to this event in another part of the application. For example, check the code for this link .

0


source







All Articles