use newSingleThreadContext instead of mutex for token refresh

fixes #57
This commit is contained in:
Jannik 2022-05-20 15:07:07 +02:00
parent ef9a0f00d0
commit bc5509cf93
Signed by: Seil0
GPG Key ID: E8459F3723C52C24
2 changed files with 6 additions and 5 deletions

View File

@ -38,6 +38,9 @@ android {
}
kotlinOptions {
jvmTarget = '1.8'
kotlin.sourceSets.all {
languageSettings.optIn("kotlin.RequiresOptIn")
}
}
namespace 'org.mosad.teapod'
}

View File

@ -33,8 +33,6 @@ import io.ktor.client.request.forms.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
@ -59,7 +57,8 @@ object Crunchyroll {
private lateinit var token: Token
private var tokenValidUntil: Long = 0
private val tokeRefreshMutex = Mutex()
@OptIn(DelicateCoroutinesApi::class)
private val tokenRefreshContext = newSingleThreadContext("TokenRefreshContext")
private var accountID = ""
@ -141,8 +140,7 @@ object Crunchyroll {
params: List<Pair<String, Any?>> = listOf(),
bodyObject: Any = Any()
): T = coroutineScope {
// TODO find a better way to make token refresh thread safe, currently it's blocking
tokeRefreshMutex.withLock {
withContext(tokenRefreshContext) {
if (System.currentTimeMillis() > tokenValidUntil) refreshToken()
}