-1

I am trying to make an application that users can send posts. When user send a post, two different data should be written. First data to change is total number of the posts. Second one is the post itself. I use realtime-database and use a transaction to change the total number of the posts. I use transaction to prevent concurrent writes to damage the application. Now, i run the transaction and then if the transaction is committed, i send the post data to database.

totalNumberOfPostsReference.runTransaction(new Transaction.Handler {

 @NonNull
 @Override
 public Transaction.Result doTransaction(@NonNull MutableData currentData) {
        String data = currentData.getValue().toString();
        long incrementVal = Long.valueOf(data) + 1;
        currentData.setValue(String.valueOf(incrementVal));

        return Transaction.success(currentData);
        }

 @Override
 public void onComplete(@Nullable DatabaseError error, boolean committed, @Nullable DataSnapshot currentData) {
      if(committed){
            Post post = new Post(val1, val2, val3);
            userPostReference.setValue(post);
      }
 }
});

If the user's network connection is gone when total number of posts has changed but post itself has not been sent to database yet, this causes problems. I want to make multi-locational update and also to run transaction to prevent the concurrent writes. I read this, some other firebase blogs and a few questions on that topic in stackoverflow, but they did not helped me exactly.

I guess there is a way to use both transactions and batched writes in firebase cloud firestore, but how to handle my problem for firebase realtime database?

**EDIT : ** I know that it's a bad idea but my value stored as type of String instead of an integer. What to do in this scenario?

gxslash
  • 124
  • 1
  • 11
  • 1
    Transactions simply do not work without a network connection. Are you expecting different behavior? – Doug Stevenson Sep 08 '20 at 22:06
  • No, what i mean is that transaction is committed then program send post to database. But if task is unsuccessful when post is being sent, total number of posts will be increased, but post will not be sent. Am i wrong?? – gxslash Sep 09 '20 at 00:21

1 Answers1

0

Realtime Database does not allow for multi-location transactions like Firestore. With Firestore, you can work with documents in various collections with no problem. With Realtime Database, you can only safely work with children under the location you used for the transaction.

Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380