I am fetching messages every second after the previous call was successful. The problem is, sometimes it takes 2 seconds for the call to finish. During that time, I can navigate back, choose another person and open the conversation with him.
Now, the previous call is successful and populates the area with both conversation data from UserA, and UserB. Furthermore, it continuously fetches the conversations for both UserA, and UserB.
I am suspecting that perhaps I should use clearTimeout(interval) instead of clearTimeout(fetchConversationInterval), or use better code?
But also, how can I abort the still unfinished call if the user navigates back while the messages are being fetched?
I have the following code:
In data()
fetchConversationInterval: null,
On mounted():
this.messagesFetchingInterval()
And on beforeDestroy()
clearTimeout(this.fetchConversationInterval)
In methods:
async messagesFetchingInterval () {
let that = this
this.fetchConversationInterval = setTimeout(async function interval () {
await that.getConversation(that.peerProfile.user_id)
.finally(()=> {
if (that.currentRoute === '/direct-messages/conversation') {
that.fetchConversationInterval = setTimeout(interval, 1000)
}
})
}, 1000)
},
Async functions (in your case - getConversation) returns their subscription. you can save it in a parameter and then unsubscribe it in on destroy.
var mySubscription;
this.mySubscription = someAsyncFunc().subscribe((result) => {
console.log(result);
})
ngOnDestroy(){
this.mySubscription.unsubscribe();
}