Skip to content

Instantly share code, notes, and snippets.

@simpulton
Last active June 21, 2016 05:21
Show Gist options
  • Save simpulton/7867239 to your computer and use it in GitHub Desktop.
Save simpulton/7867239 to your computer and use it in GitHub Desktop.
A real-time presence service using Firebase and AngularJS.
app.controller('MainCtrl', ['$scope', 'PresenceService', function ($scope, PresenceService) {
$scope.totalViewers = 0;
$scope.$on('onOnlineUser', function(){
$scope.$apply(function () {
$scope.totalViewers = PresenceService.getOnlineUserCount();
});
});
}]);
app.factory('PresenceService', ['$rootScope', function($rootScope){
var onlineUsers = 0;
var listRef = new Firebase('https://<url>.firebaseio.com/presence/');
var userRef = listRef.push();
// Add ourselves to presence list when online.
var presenceRef = new Firebase('https://<url>.firebaseio.com/.info/connected');
presenceRef.on('value', function (snap) {
if (snap.val()) {
userRef.set(true);
// Remove ourselves when we disconnect.
userRef.onDisconnect().remove();
}
});
// Number of online users is the number of objects in the presence list.
listRef.on('value', function (snap) {
onlineUsers = snap.numChildren();
$rootScope.$broadcast('onOnlineUser');
});
var getOnlineUserCount = function() {
return onlineUsers;
}
return {
getOnlineUserCount: getOnlineUserCount
}
}]);
@panconjugo
Copy link

Any idea about why it does not work in a different view? I use {{totalViewers}} in a different view but it returns to 0, I have to reload the site to be able to see the real number.

@DavidGoussev
Copy link

I think the onDisconnect call should go before the userRef.setstatement so you minimize the chances of ghost user leftover (logged-on user initiating a logout call that resolves before code makes it to onDisconnect)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment