Last active
April 12, 2018 15:40
-
-
Save tensory/ef57d635f54bdba8f378643cea01a918 to your computer and use it in GitHub Desktop.
Blocking token request example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object AuthManager { | |
private val asyncTokenProvider = AsyncTokenProvider() | |
var accessToken: String? = null | |
get() = asyncTokenProvider.getAccessToken() | |
fun getTokens() { | |
Thread(asyncTokenProvider).start() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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