Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class FirebaseGameSynchronizer implements ChildEventListener {
private DatabaseReference mMovesRecordList;
private Modulator mMessageModulator;
private int mMoveIndex;
private int mSelfMoveSoph;
private boolean mSynced;
private ArrayDeque<String> mUnsyncBuffer = new ArrayDeque<>();
private void resyncAll() {
while (!mUnsyncBuffer.isEmpty())
mMessageModulator.onReceiveMove(true, mUnsyncBuffer.pop());
}
boolean isSynced = false;
private FirebaseGameSynchronizer(DatabaseReference movesRecordList,
Modulator messageModulator) {
mMovesRecordList = movesRecordList;
mMessageModulator = messageModulator;
mMoveIndex = 0;
mSelfMoveSoph = 0;
mMovesRecordList.addChildEventListener(this);
}
public int moveCount() {
return mMoveIndex;
}
public String recordPath () {
return mMovesRecordList.getPath().toString();
}
public void attachModulator(Modulator modulator) {
mMessageModulator = modulator;
}
public void detachModulator() {
mMessageModulator = null;
}
public void startSync() {
if (!isSynced) {
resyncAll();
isSynced = true;
return;
}
}
public void stopSync() {
isSynced = false;
}
public void flush() {
mMovesRecordList.removeEventListener(this);
}
public void sendMoveMsg(String moveValue) {
++mSelfMoveSoph;
FirebaseDatabase.getInstance().getReference(mMovesRecordList.getPath() + "/M" + mMoveIndex)
.setValue(moveValue);
}
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
if (mSelfMoveSoph > 0) {
--mSelfMoveSoph;
++mMoveIndex;
return;
}
if (!isSynced && dataSnapshot.getKey().charAt(0) == 'M') {
mUnsyncBuffer.add(dataSnapshot.getValue(String.class));
++mMoveIndex;
return;
}
Log.d("FirebaseGameSync", "Real-sync");
mMessageModulator.onReceiveMove(false, dataSnapshot.getValue(String.class));
++mMoveIndex;
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Log.e("FirebaseGameSync", "onChildChanged not supported");
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
Log.e("FirebaseGameSync", "onChildRemoved not supported");
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Log.e("FirebaseGameSync", "onChildMoved not supported");
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e("FirebaseGameSync", "onCancelled not supported");
}
public static FirebaseGameSynchronizer newInstance(String moveListRecordPath,
Modulator modulator) {
return new FirebaseGameSynchronizer(FirebaseDatabase.getInstance()
.getReference(moveListRecordPath), modulator);
}
public interface Modulator {
public void onReceiveMove(boolean isSyncingPast, String encodedMsg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.