parent
e01eb46bfc
commit
1db8d74111
@ -0,0 +1,72 @@ |
|||||||
|
package com.otaliastudios.cameraview; |
||||||
|
|
||||||
|
import android.support.annotation.NonNull; |
||||||
|
|
||||||
|
import java.util.concurrent.CountDownLatch; |
||||||
|
import java.util.concurrent.TimeUnit; |
||||||
|
|
||||||
|
/** |
||||||
|
* A naive implementation of {@link java.util.concurrent.CountDownLatch} |
||||||
|
* to help in testing. |
||||||
|
*/ |
||||||
|
class Task<T> { |
||||||
|
|
||||||
|
private CountDownLatch mLatch; |
||||||
|
private T mResult; |
||||||
|
private int mCount; |
||||||
|
|
||||||
|
Task() { |
||||||
|
} |
||||||
|
|
||||||
|
private boolean listening() { |
||||||
|
return mLatch != null; |
||||||
|
} |
||||||
|
|
||||||
|
void listen() { |
||||||
|
if (listening()) throw new RuntimeException("Should not happen."); |
||||||
|
mResult = null; |
||||||
|
mLatch = new CountDownLatch(1); |
||||||
|
} |
||||||
|
|
||||||
|
void start() { |
||||||
|
if (!listening()) mCount++; |
||||||
|
} |
||||||
|
|
||||||
|
void end(T result) { |
||||||
|
if (mCount > 0) { |
||||||
|
mCount--; |
||||||
|
return; |
||||||
|
} |
||||||
|
|
||||||
|
if (listening()) { // Should be always true.
|
||||||
|
mResult = result; |
||||||
|
mLatch.countDown(); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
T await() { |
||||||
|
try { |
||||||
|
mLatch.await(); |
||||||
|
} catch (Exception e) { |
||||||
|
e.printStackTrace(); |
||||||
|
} |
||||||
|
T result = mResult; |
||||||
|
mResult = null; |
||||||
|
mLatch = null; |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
T await(long time, @NonNull TimeUnit unit) { |
||||||
|
try { |
||||||
|
mLatch.await(time, unit); |
||||||
|
} catch (Exception e) { |
||||||
|
e.printStackTrace(); |
||||||
|
} |
||||||
|
T result = mResult; |
||||||
|
mResult = null; |
||||||
|
mLatch = null; |
||||||
|
return result; |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
} |
Loading…
Reference in new issue