Promise in Kotlin with Android

Viewed 4329

How do we achieve the promise pattern in Android?. Here I ended up in a situation like before taking a user to the Home screen I want to check whether all the necessary components are loaded or not? Something like

    loadLibA().
        then().
loadLibB().
then().
loadLibc().
then()
}```

2 Answers

In Kotlin you would use coroutines, which works like promises under the hood, but looks like simple serial code:

suspend fun loadLibA() { ... }
suspend fun loadLibB() { ... }
suspend fun loadLibC() { ... }

GlobalScope.launch(Dispatchers.Main) {
    loadLibA() // Execution will stop here without blocking, until Lib A is loaded
    loadLibB() // Same as for A
    loadLibc() // Same as for A
    startHomeScreen() // Normal call to launch Home screen
}

The sample code is of course simplified just to convey the idea. You can start learning about them from official docs.

You can implement the promise patter like

fun postItem(item: Item) {
preparePostAsync() 
    .thenCompose { token -> 
        submitPostAsync(token, item)
    }
    .thenAccept { post -> 
        processPost(post)
    }

}

fun preparePostAsync(): Promise<Token> {
// makes request an returns a promise that is completed later
return promise 
}

Please refer this link Asynchronous Programming Techniques Kotlin

Related