Skip to content

Instantly share code, notes, and snippets.

View KhomDrake's full-sized avatar

Vinicius Viana KhomDrake

View GitHub Profile
suspend fun makeLogin(login: String, password: String, callback: (Token) -> Unit) {
// request login
callback(token)
}
suspend fun loadMovies(callback: (List<Movie>) -> Unit) {
makeLogin("someValue", "someValue") { token ->
// request movies with token
callback(movies)
}
suspend fun makeLogin(login: String, password: String) : Token {
// request login
return token
}
suspend fun loadMovies(token: Token) : List<Movie> {
val token = makeLogin("someValue", "someValue")
// request movies with token
return movies
}
mathScope.launch {
// calculate PI
}
mathScope.cancel()
mathScope.launch {
if(mathScope.ensureActive()) { // ensures that the scope is active and if not, it will throw a exception.
// continue the calculation
}
if(mathScope.isActive) { // returns true or false if the scope is active or not
// continue the calculation
}
}
val mathScope = CoroutineScope(Job() + Dispatchers.IO)
mathScope.launch(Job()) {
}
val launchJob = mathScope.launch {
}
launchJob.cancel()
fun loadMovies() {
backgroundScope.launch {
val movies = loadMovies() // load the movies on the background thread
launch(Dispatchers.Main) { // to touch the views to show the movies, we need to launch another coroutine in the main thread
showMovies(movies)
}
}
}
fun loadMovies() {
mainScope.launch {
val movies = withContext(Dispatchers.IO) { // launch a coroutine in another Dispatcher and return the result
loadMovies()
}
showMovies(movies)
}
}