java - Is this a convenient way of running code in a background thread and return a result via a callback executed in the calling thread? -
in last days have found myself using approach asynchronously performing long operation (several seconds), , return value via callback must execute on caller thread, typically but not necessarily ui thread.
public abstract class dosomethingcallback { public abstract void done(object result); } public void dosomething(final object param, final dosomethingcallback dosomethingcallback) { // instantiate handler calling thread final handler handler = new handler(); // start running long operation in thread new thread(new runnable() { @override public void run() { // long operation using "param" input... object result = longoperation(param); // return result via callback, run in caller thread handler.post(new runnable() { @override public void run() { dosomethingcallback.done(clearbytes); } }); } }).start(); }
this seems work pretty , simple use. however, somehow suspect might have problems i'm not aware of. question is, what potential issues of approach? better alternatives manually creating , running thread? i'm seeking simplicity , robustness.
the problem such approach breaks encapsulation: second thread not computes result, dictates caller thread should it. i'd better refactor code follows:
public abstract class dosomethingcallback { final handler handler = new handler(); public void post(final object result) { handler.post(new runnable() { @override public void run() { dosomethingcallback.done(result); } }); } public abstract void done(object result); } public void dosomething(final object param, final dosomethingcallback dosomethingcallback) { // instantiate handler calling thread final dosomethingcallback handler = new dosomethingcallback () { void done(object result) { ... } }; // start running long operation in thread new thread(new runnable() { @override public void run() { // long operation using "param" input... object result = longoperation(param); // return result via callback, run in caller thread handler.post(result); }); } }).start(); }
Comments
Post a Comment