Skip to content

Instantly share code, notes, and snippets.

@smaugho
Last active September 1, 2017 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smaugho/77b5ecddf02bb109cc1614db1b7e5200 to your computer and use it in GitHub Desktop.
Save smaugho/77b5ecddf02bb109cc1614db1b7e5200 to your computer and use it in GitHub Desktop.
Code
public void loadChats() {
final User_ currentUser = authenticateManager.getCurrentUser();
if (currentUser != null) {
//Fetch all the teachers associated to this student
$FirebaseDatabase("/associations/{currentUser.getUserId()}/teachers").model(User_.class).setKeyIntoField("userId");
if ($FirebaseDatabase.MultipleValues) {
List<Chat_> chats = new LinkedList<>();
List<User_> teachers = $inject("values");
//Fetch all the chats associated
$FirebaseDatabase("/chats").model(Chat_.class).setKeyIntoField("chatId")
.getPathReference().orderByChild("users/" + currentUser.getUserId() + "/userId")
.equalTo(currentUser.getUserId());
if ($FirebaseDatabase.MultipleValues) {
List<Chat_> existingChats = $inject("values");
Set<String> existingTeachersId = new HashSet<>();
for (Chat_ chat : existingChats) {
chats.add(chat);
existingTeachersId.addAll(chat.getUsers().keySet());
}
for (final User_ teacher : teachers) {
//Create "virtual" chats
if (!existingTeachersId.contains(teacher.getUserId())) {
Chat_ virtualChat = new Chat_();
virtualChat.setUsers(new HashMap<String, User_>() {{
put(currentUser.getUserId(), currentUser);
put(teacher.getUserId(), teacher);
}});
chats.add(virtualChat);
}
}
$ChatsLoaded(chats);
listenExistingChats(existingChats);
}
if ($FirebaseDatabase.NotExists) {
for (final User_ teacher : teachers) {
//Create "virtual" chats
Chat_ chat = new Chat_();
chat.setUsers(new HashMap<String, User_>() {{
put(currentUser.getUserId(), currentUser);
put(teacher.getUserId(), teacher);
}});
chats.add(chat);
}
$ChatsLoaded(chats);
}
}
if ($FirebaseDatabase.NotExists) {
$ChatsLoaded(new LinkedList<Chat_>());
}
}
}
protected void listenExistingChats(List<Chat_> existingChats) {
for (Chat_ chat : existingChats) {
listenExistingChat(chat);
}
}
protected void listenExistingChat(Chat_ chat) {
if (!chatsBeingListened.containsKey(chat.getChatId())) {
FirebaseDatabaseActionHolder.FirebaseValueListener listener =
$FirebaseDatabase("/messages/{chat.getChatId()}").keepSynced(true)
.model(Message_.class)
.setKeyIntoField("messageId")
.listenChildValues();
if ($FirebaseDatabase.ChildAdded) {
Message_ message = $inject("value");
$MessageAdded(message);
}
chatsBeingListened.put(chat.getChatId(), listener);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment