Skip to content

Instantly share code, notes, and snippets.

@tensory
Last active April 12, 2018 15:40
Show Gist options
  • Save tensory/ef57d635f54bdba8f378643cea01a918 to your computer and use it in GitHub Desktop.
Save tensory/ef57d635f54bdba8f378643cea01a918 to your computer and use it in GitHub Desktop.
Blocking token request example
internal class AsyncTokenProvider : Runnable {
val lock = ReentrantLock()
val requestCondition = lock.newCondition()
var done = false
interface AsyncTokenListener {
fun onEvent(foo: String)
}
var result: String = "Not Done"
override fun run() {
lock.lock()
Log.d("AsyncTokenProvider", "Starting run")
try {
var sum = 1000000000
while (sum > 0) {
sum -= 1
Log.d("AsyncTokenProvider", "Counting down...")
}
result = "Done"
done = true
requestCondition.signal()
} finally {
lock.unlock()
}
}
fun getAccessToken(): String {
lock.lock()
try {
while (!done) {
Log.d("AsyncTokenProvider", "Waiting...")
requestCondition.await()
}
Log.d("AsyncTokenProvider", "Done, result is $result")
return result
} finally {
lock.unlock()
}
}
}
object AuthManager {
private val asyncTokenProvider = AsyncTokenProvider()
var accessToken: String? = null
get() = asyncTokenProvider.getAccessToken()
fun getTokens() {
Thread(asyncTokenProvider).start()
}
}
// in onCreate
Log.d("MainActivity", "onCreate")
AuthManager.getTokens()
val myToken = AuthManager.accessToken
Log.d("MainActivity", "$myToken")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment