Can i return a value from a function and have the function keep running code
I am implementing an interface.
I have two functions that I have to implement A and B. A checks the file is not corrupt and return then B processes the file and returns. after B return function C ru开发者_开发百科ns, I have no control over C as I am just implementing A and B.
The problem is that B takes a long time to run and C needs it return value to run. Ideally I would split B into B and D and put all the stuff that C dose not need to run into D. As this is impossible I want to know if it is possible to return a value from B so C can run but afterwards then have B run more code.
C cannot be called from B.
A
must call B
and C
You want B
to do some processing, C
to be called and B
to continue processing.
The simplest approach is to have
A
called a method on B
which opens the file and does some processing, and leaves anything open which is need later. A
calls C
and then calls another method on B
which finishes the processing. This means B
must know when to stop and return so C
can be called.
The way around this is to use a listener interface below.
class A {
void method(B b, C c) {
b.function(new Listener() {
public void onValue(long num) { // or any event type
if (num > 100) C.something();
}
});
}
}
This way B
has no idea when C
will be called.
You can implement a listener interface which you pass to the function and it can "return" multiple values. However once a function actually return
s it is no longer running.
This function can run in another thread or the same thread.
interface Listener {
public void onValue(long num);
public void onError(Exception e);
public void onEndOfData();
}
public void function(Listener l) {
try {
for(int i=0;i<10;i++) l.onValue(i);
// read a file
} catch (Exception e) {
l.onError(e);
} finally {
l.onEndOfData();
}
}
put another way instead of doing something like
// only one value.
long value = function();
System.out.println("value returned was "+value);
you can do
// any number of values can be returned
// and the function can keep processing.
function(new Listener() {
public void onValue(long value) {
System.out.println("value returned was "+value);
}
});
You could have B schedule the long-running task to execute on another thread (eg a Timer or Executor) then return the value without having to wait for the long-running task to complete.
精彩评论