Java 类com.google.firebase.database.MutableData 实例源码

项目:Programmers    文件:Worker.java   
public static void runPostViewsCountTransition(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post post = mutableData.getValue(Post.class);
            if (post == null) {
                return Transaction.success(mutableData);
            }

            int viewsCount = post.getViews() + 1;

            post.setViews(viewsCount);
            mutableData.setValue(post);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            showLog("runCommentsCountTransition " + (databaseError != null));

                    /* if (databaseError == null) {
                        errorListener.onError();
                    }*/
        }
    });
}
项目:social-app-android    文件:DatabaseHelper.java   
public void updateProfileLikeCountAfterRemovingPost(Post post) {
    DatabaseReference profileRef = database.getReference("profiles/" + post.getAuthorId() + "/likesCount");
    final long likesByPostCount = post.getLikesCount();

    profileRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= likesByPostCount) {
                mutableData.setValue(currentValue - likesByPostCount);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating likes count transaction is completed.");
        }
    });

}
项目:social-app-android    文件:DatabaseHelper.java   
public void decrementCommentsCount(String postId, final OnTaskCompleteListener onTaskCompleteListener) {
    DatabaseReference postRef = database.getReference("posts/" + postId + "/commentsCount");
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= 1) {
                mutableData.setValue(currentValue - 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating comments count transaction is completed.");
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(true);
            }
        }
    });
}
项目:social-app-android    文件:DatabaseHelper.java   
public void incrementWatchersCount(String postId) {
    DatabaseReference postRef = database.getReference("posts/" + postId + "/watchersCount");
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue == null) {
                mutableData.setValue(1);
            } else {
                mutableData.setValue(currentValue + 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating Watchers count transaction is completed.");
        }
    });
}
项目:RxFirebase2    文件:RunTransactionOnSubscribe.java   
@Override public void subscribe(final CompletableEmitter emitter) {
  final Transaction.Handler handler = new Transaction.Handler() {
    @Override public Transaction.Result doTransaction(MutableData mutableData) {
      try {
        return task.apply(mutableData);
      } catch (Exception e) {
        //TODO: Is this enough?
        throw new RuntimeException(e);
      }
    }

    @Override public void onComplete(DatabaseError databaseError, boolean committed,
        DataSnapshot dataSnapshot) {
      if (!emitter.isDisposed()) {
        if (null == databaseError) {
          emitter.onComplete();
        } else {
          emitter.onError(databaseError.toException());
        }
      }
    }
  };

  ref.runTransaction(handler, fireLocalEvents);
}
项目:gaso    文件:MilestoneDAO.java   
public void doTransaction(String uid, final OnMilestoneTransaction listener){
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if(user!=null) {
        String key;
        if(uid==null || uid.isEmpty())
            return;
        DatabaseReference mRef = mDatabase.child(Constants.FIREBASE_MILESTONES).child(user.getUid()).child(SessionSingleton.getInstance().currentCar.getid()).child(uid);
        mRef.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Milestone milestone = mutableData.getValue(Milestone.class);
                if(milestone==null)
                    return Transaction.success(mutableData);
                milestone = listener.onTransaction(milestone);
                mutableData.setValue(milestone);
                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

            }
        });
    }
}
项目:SpotiQ    文件:PartiesRepository.java   
public void incrementUserSongRequestCount(String partyTitle, String userId) {
    databaseReference
        .child(partyTitle)
        .child(FirebaseConstants.CHILD_USERS)
        .child(userId)
        .child(FirebaseConstants.CHILD_USERS_SONGS_REQUESTED)
        .runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData currentData) {
                if (currentData.getValue() == null) {
                    currentData.setValue(1);
                }
                else {
                    currentData.setValue((Long) currentData.getValue() + 1);
                }
                return Transaction.success(currentData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

            }
        });
}
项目:Roach    文件:DecksInteractorFirebase.java   
@Override
public void setLeader(String deckId, final String leaderId) {
    DatabaseReference deckReference = mUserReference.child(deckId).child("leaderId");

    // Transactions will ensure concurrency errors don't occur.
    deckReference.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            // Set value and report transaction success.
            mutableData.setValue(leaderId);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Do nothing.
        }
    });
}
项目:Roach    文件:DecksInteractorFirebase.java   
@Override
public void renameDeck(final String deckId, final String newName) {
    DatabaseReference deckReference = mUserReference.child(deckId).child("name");

    // Transactions will ensure concurrency errors don't occur.
    deckReference.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            // Set value and report transaction success.
            mutableData.setValue(newName);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Do nothing.
        }
    });
}
项目:Roach    文件:DecksInteractorFirebase.java   
@Override
public void deleteDeck(final String deckId) {
    DatabaseReference deckReference = mUserReference.child(deckId).child("deleted");

    // Transactions will ensure concurrency errors don't occur.
    deckReference.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            // Set value and report transaction success.
            mutableData.setValue(true);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Do nothing.
        }
    });
}
项目:Quadro    文件:PostListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:showcase-android    文件:RxFirebaseDatabase.java   
/**
 * Run a transaction on the data at this location. For more information on running transactions, see
 *
 * @param ref              reference represents a particular location in your database.
 * @param fireLocalEvents  boolean which allow to receive calls of your transaction in your local device.
 * @param transactionValue value of the transaction.
 * @return a {@link Single} which emits the final {@link DataSnapshot} value if the transaction success.
 */
@NonNull
public static Single<DataSnapshot> runTransaction(@NonNull final DatabaseReference ref,
                                                  @NonNull final boolean fireLocalEvents,
                                                  @NonNull final long transactionValue) {
   return Single.create(new SingleOnSubscribe<DataSnapshot>() {
      @Override public void subscribe(final SingleEmitter emitter) throws Exception {
         ref.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
               Integer currentValue = mutableData.getValue(Integer.class);
               if (currentValue == null) {
                  mutableData.setValue(transactionValue);
               } else {
                  mutableData.setValue(currentValue + transactionValue);
               }
               return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
               if (databaseError != null) {
                  emitter.onError(new RxFirebaseDataException(databaseError));
               } else {
                  emitter.onSuccess(dataSnapshot);
               }
            }
         }, fireLocalEvents);
      }
   });
}
项目:gdx-fireapp    文件:Database.java   
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public <T, R extends T> void transaction(final Class<T> dataType, final TransactionCallback<R> transactionCallback, final CompleteCallback completeCallback)
{
    databaseReference().runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData)
        {
            R transactionData = null;
            if (dataType == List.class || dataType == Map.class) {
                transactionData = (R) mutableData.getValue();
            } else {
                transactionData = (R) mutableData.getValue(dataType);
            }
            mutableData.setValue(transactionCallback.run(transactionData));
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot)
        {
            if (completeCallback == null) return;
            if (databaseError != null) {
                completeCallback.onError(databaseError.toException());
            } else {
                completeCallback.onSuccess();
            }
        }
    });
    terminateOperation();
}
项目:Programmers    文件:Transations.java   
/**
 * Decrement or increment commentsCount
 *
 * @param postRef   the Post reference to run transaction
 * @param increment if TRUE it wil increment, if FALSE it will decrement.
 */
public static void runCommentsCountTransition(DatabaseReference postRef, final boolean increment) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post post = mutableData.getValue(Post.class);
            if (post == null) {
                return Transaction.success(mutableData);
            }

            int commentsCount = post.getCommentsCount();
            int data = increment ? commentsCount + 1 : commentsCount - 1;

            post.setCommentsCount(data);

            //update localy
            RepositoryManager.getInstance()
                    .getPostsRepository()
                    .updateLocaly(post);

            mutableData.setValue(post);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            showLog("runCommentsCountTransition: " + (databaseError != null));
        }
    });
}
项目:quickstart-android    文件:PostListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:Attendance    文件:PostListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:Attendance    文件:AbsTypesListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:Attendance    文件:AttendanceListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:Attendance    文件:IntsListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:Attendance    文件:AbsenceListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:KeralaAttractions    文件:DetailActivity.java   
private void onLikeClicked(final DatabaseReference likeRef) {
    likeRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Photo p = mutableData.getValue(Photo.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.likes.containsKey(mUserId)) {
                // Unlike the photo and remove self from likes
                p.starCount = p.starCount - 1;
                p.likes.remove(mUserId);
                Log.d(TAG, "doTransaction: Unlike");
            } else {
                // Like the photo
                Log.d(TAG, "doTransaction: Like");
                p.starCount = p.starCount + 1;
                p.likes.put(mUserId, true);
            }
            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:TvAppRepo    文件:RepoDatabase.java   
public void incrementApkDownloads(Apk app) {
    databaseReference.child(app.getKey()).child("downloads").runTransaction(
            new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Long updatedViews = mutableData.getValue(Long.class) + 1;
            mutableData.setValue(updatedViews);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
        }
    });
}
项目:TvAppRepo    文件:RepoDatabase.java   
public void incrementApkViews(Apk app) {
    databaseReference.child(app.getKey()).child("views").runTransaction(
            new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Long updatedViews = mutableData.getValue(Long.class) + 1;
            mutableData.setValue(updatedViews);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
        }
    });
}
项目:IEEE_Malabar    文件:PostListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:LivePokemonFinder    文件:PostsAdapter.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d("PostAdapter", "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:firebase-quickstart-android    文件:PostListFragment.java   
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
项目:AR-Trace    文件:FirebaseClient.java   
private void sendTraceLikeToFirebase(final boolean isLikeClicked, final Trace trace) {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    final DatabaseReference myRef = database.getReference("building").child(trace.getLocationID()).child("trace").child(trace.getTraceID());

    myRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            MutableData likeNumData = mutableData.child("likeNum");
            MutableData likeUserListData = mutableData.child("likeUserList").child(User.getMyInstance().getUserId());
            Object likeNum = likeNumData.getValue();
            if(likeNum == null)
                return Transaction.success(mutableData);

            if(isLikeClicked) {
                likeNumData.setValue((long) likeNum + 1);
                likeUserListData.setValue(true);
            }
            else {
                likeNumData.setValue((long) likeNum - 1);
                likeUserListData.setValue(null);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            if(databaseError != null) {
            }
        }
    });
}
项目:Roach    文件:DecksInteractorFirebase.java   
@Override
public void addCardToDeck(final String deckId, final CardDetails card) {
    DatabaseReference deckReference = mUserReference.child(deckId).child("cardCount");

    // Transactions will ensure concurrency errors don't occur.
    deckReference.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Map<String, Long> cards = (Map<String, Long>) mutableData.getValue();

            if (cards == null) {
                cards = new HashMap<String, Long>();
            }

            if (!canAddCard(cards, card)) {
                return Transaction.success(mutableData);
            }

            if (cards.containsKey(card.getIngameId())) {
                // If the user already has at least one of these cards in their deck.
                long currentCardCount = cards.get(card.getIngameId());
                cards.put(card.getIngameId(), currentCardCount + 1);
            } else {
                // Else add one card to the deck.
                cards.put(card.getIngameId(), 1L);
            }

            // Set value and report transaction success.
            mutableData.setValue(cards);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Do nothing.
        }
    });
}
项目:Roach    文件:DecksInteractorFirebase.java   
@Override
public void removeCardFromDeck(final String deckId, final CardDetails card) {
    DatabaseReference deckReference = mUserReference.child(deckId).child("cardCount");

    // Transactions will ensure concurrency errors don't occur.
    deckReference.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Map<String, Long> cards = (Map<String, Long>) mutableData.getValue();

            if (cards.containsKey(card.getIngameId())) {
                // If the user already has at least one of these cards in their deck.
                long currentCardCount = cards.get(card.getIngameId());
                long newCount = currentCardCount - 1;

                if (newCount == 0) {
                    cards.remove(card.getIngameId());
                } else {
                    cards.put(card.getIngameId(), newCount);
                }
            } else {
                // This deck doesn't have that card in it.
            }

            // Set value and report transaction success.
            mutableData.setValue(cards);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Do nothing.
        }
    });
}
项目:Rx2Firebase    文件:RxFirebaseDatabase.java   
/**
 * Run a transaction on the data at this location. For more information on running transactions, see
 *
 * @param ref              reference represents a particular location in your database.
 * @param fireLocalEvents  boolean which allow to receive calls of your transaction in your local device.
 * @param transactionValue value of the transaction.
 * @return a {@link Single} which emits the final {@link DataSnapshot} value if the transaction success.
 */
@NonNull
public static Single<DataSnapshot> runTransaction(@NonNull final DatabaseReference ref,
                                                  @NonNull final boolean fireLocalEvents,
                                                  @NonNull final long transactionValue) {
   return Single.create(new SingleOnSubscribe<DataSnapshot>() {
      @Override public void subscribe(final SingleEmitter emitter) throws Exception {
         ref.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
               Integer currentValue = mutableData.getValue(Integer.class);
               if (currentValue == null) {
                  mutableData.setValue(transactionValue);
               } else {
                  mutableData.setValue(currentValue + transactionValue);
               }
               return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
               if (databaseError != null) {
                  emitter.onError(new RxFirebaseDataException(databaseError));
               } else {
                  emitter.onSuccess(dataSnapshot);
               }
            }
         }, fireLocalEvents);
      }
   });
}
项目:rxfirebase    文件:RxValue.java   
/**
 * @param ref
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> transaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            ref.runTransaction(transaction(emit, function));
        }
    });
}
项目:rxfirebase    文件:RxValue.java   
/**
 * @param ref
 * @param function
 * @param fireLocalEvents
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> transaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function,
        final boolean fireLocalEvents) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            ref.runTransaction(transaction(emit, function), fireLocalEvents);
        }
    });
}
项目:rxfirebase    文件:RxValue.java   
/**
 * @param emitter
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
        @NonNull final SingleEmitter<DataSnapshot> emitter,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            try {
                return function.apply(mutableData);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onComplete(@Nullable DatabaseError databaseError,
                               boolean committed,
                               @NonNull DataSnapshot dataSnapshot) {
            if (!emitter.isDisposed()) {
                if (null == databaseError) {
                    emitter.onSuccess(dataSnapshot);
                } else {
                    emitter.onError(databaseError.toException());
                }
            }
        }
    };
}
项目:rxfirebase    文件:RxFirebaseDatabase.java   
/**
 * @param ref
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> runTransaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return RxValue.transaction(ref, function);
}
项目:rxfirebase    文件:RxFirebaseDatabase.java   
/**
 * @param ref
 * @param fireLocalEvents
 * @param function
 * @return
 * ref.runTransaction(handler, fireLocalEvents);
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> runTransaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function,
        final boolean fireLocalEvents) {
    return RxValue.transaction(ref, function, fireLocalEvents);
}
项目:Programmers    文件:Transations.java   
public static void runReputationCountTransition(String userId, final boolean increment, final boolean isPost) {

        Library.getUserRef(userId).runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Usuario user = mutableData.getValue(Usuario.class);
                if (user == null) {
                    return Transaction.success(mutableData);
                }

                int reputationCount = user.getReputation();
                if (increment && isPost) {
                    reputationCount += ReputationConfigs.POST_INCREMENT;
                } else if (!increment && isPost) {
                    reputationCount -= ReputationConfigs.POST_DECREMENT;
                } else if (increment) {
                    reputationCount += ReputationConfigs.COMMENT_INCREMENT;
                } else {
                    reputationCount -= ReputationConfigs.COMMENT_DECREMENT;
                }

                String userCodeLevel = user.getCodeLevel();
                if (reputationCount < 385) { // user help less than 25 peoples
                    userCodeLevel = Programmers.getContext().getString(R.string.beginner);
                } else if (reputationCount >= 385 && reputationCount < 770) { // user help 25 peoples
                    userCodeLevel = Programmers.getContext().getString(R.string.amauter);
                } else if (reputationCount >= 770 && reputationCount < 1540) { // user help 50 peoples
                    userCodeLevel = Programmers.getContext().getString(R.string.professional);
                } else if (reputationCount >= 3080) { // user help more than 100 or more  peoples
                    userCodeLevel = Programmers.getContext().getString(R.string.expert);
                }

                user.setReputation(reputationCount);
                user.setCodeLevel(userCodeLevel);

                //update user data localy
                RepositoryManager.getInstance().getUsersRepository()
                        .updateLoggedUser(user);

                mutableData.setValue(user);
                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
                showLog("update reputations complete: " + (databaseError != null));
            }
        });
    }
项目:RxFirebase2    文件:RunTransactionOnSubscribe.java   
RunTransactionOnSubscribe(DatabaseReference ref, boolean fireLocalEvents,
    Function<MutableData, Transaction.Result> task) {
  this.ref = ref;
  this.fireLocalEvents = fireLocalEvents;
  this.task = task;
}
项目:RxFirebase2    文件:RxFirebaseDatabase.java   
/**
 * @see DatabaseReference#runTransaction(Transaction.Handler)
 */
@NonNull @CheckResult public static Completable runTransaction(@NonNull DatabaseReference ref,
    @NonNull Function<MutableData, Transaction.Result> task) {
  return runTransaction(ref, true, task);
}
项目:RxFirebase2    文件:RxFirebaseDatabase.java   
/**
 * @see DatabaseReference#runTransaction(Transaction.Handler, boolean)
 */
@NonNull @CheckResult public static Completable runTransaction(@NonNull DatabaseReference ref,
    boolean fireLocalEvents, @NonNull Function<MutableData, Transaction.Result> task) {
  return Completable.create(new RunTransactionOnSubscribe(ref, fireLocalEvents, task));
}