From 5824e5405fcc5790cedb1808593d84778093100b Mon Sep 17 00:00:00 2001 From: Salakar Date: Fri, 24 Mar 2017 23:36:01 +0000 Subject: [PATCH] [android][database] transaction lock condition 'awaits' now timeouts after 30 seconds if not signalled (forgot to include the handler originally also) --- .../RNFirebaseTransactionHandler.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 android/src/main/java/io/invertase/firebase/database/RNFirebaseTransactionHandler.java diff --git a/android/src/main/java/io/invertase/firebase/database/RNFirebaseTransactionHandler.java b/android/src/main/java/io/invertase/firebase/database/RNFirebaseTransactionHandler.java new file mode 100644 index 00000000..7af403d8 --- /dev/null +++ b/android/src/main/java/io/invertase/firebase/database/RNFirebaseTransactionHandler.java @@ -0,0 +1,70 @@ +package io.invertase.firebase.database; + +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; + + +public class RNFirebaseTransactionHandler { + private final ReentrantLock lock; + private final Condition condition; + private Map data; + private volatile boolean isReady; + + public Object value; + public boolean interrupted; + public boolean abort = false; + + RNFirebaseTransactionHandler() { + lock = new ReentrantLock(); + condition = lock.newCondition(); + } + + /** + * Signal that the transaction data has been received + * + * @param updateData + */ + public void signalUpdateReceived(Map updateData) { + lock.lock(); + + abort = (Boolean) updateData.get("abort"); + value = updateData.get("value"); + + try { + if (isReady) + throw new IllegalStateException("This transactionUpdateCallback has already been called."); + data = updateData; + isReady = true; + condition.signalAll(); + } finally { + lock.unlock(); + } + } + + /** + * Wait for transactionUpdateReceived to signal condition + * @throws InterruptedException + */ + void await() throws InterruptedException { + lock.lock(); + Boolean notTimedOut = false; + + try { + while (!notTimedOut && !isReady) { + notTimedOut = condition.await(30, TimeUnit.SECONDS); + } + } finally { + lock.unlock(); + } + } + + /** + * Get the + * @return + */ + Map getUpdates() { + return data; + } +}