Skip to content

Commit

Permalink
add resubscribe
Browse files Browse the repository at this point in the history
  • Loading branch information
pgautier404 committed Feb 1, 2024
1 parent 3796c41 commit 3ac19de
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions app/src/main/java/com/example/moderatedchat/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
Expand Down Expand Up @@ -173,7 +174,6 @@ fun ModeratedChatLayout(
withContext(Dispatchers.IO) {
coroutineScope {
launch {
// TODO: Ok, so how do I reliably resubscribe after my token expires?
val tokenExpiresInSecs = tokenExpiresAt - (System.currentTimeMillis() / 1000)
println("token expires in $tokenExpiresInSecs")
if (topicClient == null || tokenExpiresInSecs < 10) {
Expand All @@ -199,14 +199,22 @@ fun ModeratedChatLayout(
println("cancelling existing subscribe job")
subscribeJob!!.cancelAndJoin()
}
subscribeJob = launch {
topicSubscribe(language = currentLanguage)
{
val jsonMessage = JSONObject(it)
val parsedMessage = parseMessage(jsonMessage)
currentMessages.add(parsedMessage)
println("message added to current messages list")
while (true) {
subscribeJob = launch {
topicSubscribe(language = currentLanguage)
{
val jsonMessage = JSONObject(it)
val parsedMessage = parseMessage(jsonMessage)
currentMessages.add(parsedMessage)
println("message added to current messages list")
}
}
val resubscribeAfterSecs = 180L
delay(resubscribeAfterSecs * 1000)
subscribeJob?.cancelAndJoin()
topicClient?.close()
getTopicClient(userName, userId)
print("resubscribing")
}
}
}
Expand Down Expand Up @@ -340,12 +348,11 @@ fun LanguageDropdown(
}
}


suspend fun topicSubscribe(
language: String,
onMessage: (String) -> Unit
) {
println("Subscribing to chat-$language")
println("Subscribing to chat-$language with $topicClient")
when (val response = topicClient!!.subscribe("moderator", "chat-$language")) {
is TopicSubscribeResponse.Subscription -> coroutineScope {
val subscribeBeginSecs = System.currentTimeMillis() / 1000
Expand Down

0 comments on commit 3ac19de

Please sign in to comment.