我在这里感到很困惑,最后在线上,我已经在我的项目中设置了类似的功能。如果用户按下类似按钮一次,则类似的计数器更新从0到1(喜欢)和类似的图像按钮(改变颜色)更新成功。如果按两次,计数器将从1更新为0(不像)成功。
问题是,当不同的用户也按下喜欢按钮喜欢相同的帖子时,类似的计数器不会从1更新为2.请帮忙。我希望这很清楚。以下是代码。
stream.keyBy(new KeySelector<Event, Integer>() {
@Override
public Integer getKey(Event value) throws Exception {
return value.nodeId;
}
}).window(EventTimeSessionWindows.withGap(Time.seconds(60)))
.apply(new ReduceFunction<LogRow>(), new WindowFunction<LogRow, Object, Integer, TimeWindow>())
答案 0 :(得分:1)
这应该有效。您应该使用事务来增加或减少多个人将要与之交互的值。
if (dataSnapshot.child(post_key).hasChild(auth.getCurrentUser().getUid())) {
Log.i("D Diary", "User has already Liked. So it can be considered as Unliked.");
mDatabaseLike.child(post_key).child(auth.getCurrentUser().getUid()).removeValue();
updateCounter(false);
mProcessLike = false;
} else {
Log.i("D Diary", "User Liked");
mDatabaseLike.child(post_key).child(auth.getCurrentUser().getUid()).setValue(auth.getCurrentUser().getDisplayName());
updateCounter(true)
Log.i(dataSnapshot.getKey(), dataSnapshot.getChildrenCount() + "Count");
mProcessLike = false;
}
使用updateCounter:
private void updateCounter(bool increment) {
mDatabaseLikeCount.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
if (mutableData.getValue() != null) {
int value = mutableData.getValue(Integer.class);
if(increment) {
value++;
} else {
value--;
}
mutableData.setValue(value);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "likeTransaction:onComplete:" + databaseError);
}
});
}