@@ -115,6 +115,30 @@ angular.module('mm.addons.mod_chat')
115115 return $q . reject ( ) ;
116116 }
117117
118+ // Convenience function to be called every certain time to get chat messages.
119+ function getMessagesInterval ( ) {
120+ $log . debug ( 'Polling for messages' ) ;
121+ if ( ! $mmApp . isOnline ( ) || pollingRunning ) {
122+ // Obviously we cannot check for new messages when the app is offline.
123+ return ;
124+ }
125+
126+ pollingRunning = true ;
127+
128+ return getMessages ( ) . catch ( function ( ) {
129+ // Try to login, it might have failed because the session expired.
130+ return loginUser ( ) . then ( function ( ) {
131+ return getMessages ( ) ;
132+ } ) . catch ( function ( error ) {
133+ // Fail again. Stop polling.
134+ $interval . cancel ( polling ) ;
135+ return showError ( error , 'mma.mod_chat.errorwhileretrievingmessages' ) ;
136+ } ) ;
137+ } ) . finally ( function ( ) {
138+ pollingRunning = false ;
139+ } ) ;
140+ }
141+
118142 // Check if the date should be displayed between messages (when the day changes at midnight for example).
119143 $scope . showDate = function ( message , prevMessage ) {
120144 if ( ! prevMessage ) {
@@ -142,6 +166,7 @@ angular.module('mm.addons.mod_chat')
142166 if ( beep === '' ) {
143167 $scope . newMessage . text = '' ;
144168 }
169+ getMessagesInterval ( ) ; // Update messages to show the sent message.
145170 } , function ( error ) {
146171 // Only close the keyboard if an error happens, we want the user to be able to send multiple
147172 // messages withoutthe keyboard being closed.
@@ -182,29 +207,7 @@ angular.module('mm.addons.mod_chat')
182207 }
183208
184209 // Start polling.
185- polling = $interval ( function ( ) {
186- $log . debug ( 'Polling for messages' ) ;
187- if ( ! $mmApp . isOnline ( ) || pollingRunning ) {
188- // Obviously we cannot check for new messages when the app is offline.
189- return ;
190- }
191-
192- pollingRunning = true ;
193-
194- return getMessages ( ) . catch ( function ( ) {
195- // Try to login, it might have failed because the session expired.
196- return loginUser ( ) . then ( function ( ) {
197- return getMessages ( ) ;
198- } ) . catch ( function ( error ) {
199- // Fail again. Stop polling.
200- $interval . cancel ( polling ) ;
201- return showError ( error , 'mma.mod_chat.errorwhileretrievingmessages' ) ;
202- } ) ;
203- } ) . finally ( function ( ) {
204- pollingRunning = false ;
205- } ) ;
206-
207- } , mmaChatPollInterval ) ;
210+ polling = $interval ( getMessagesInterval , mmaChatPollInterval ) ;
208211 } ) ;
209212
210213 // Removing the polling as we leave the page.
0 commit comments