Roman Elizarov
1 min readMar 20, 2017

--

Thanks a lot for this great article. May I suggest a small imporovement. You can go further with suspend keyword and change your definition of asyncTask to this:

suspend fun <T> asyncTask(function: () -> T): T {
return run(CommonPool) { function() }
}

The actual change is to replace async with run. Because of this change, the Deferred<T> result simplifies to T and see how it is easier and less error-prone to use now:

suspend fun getListOfThings() {
asyncTask { storageHelper.getListFromDb() }
.let { list ->
view.useTheResult(list)
}
}

You don’t need to remember to use await every time you use asyncTask now. You have even more safety, especially for case where you don’t otherwise need the result of your async action.

--

--

Roman Elizarov
Roman Elizarov

Written by Roman Elizarov

Project Lead for the Kotlin Programming Language @JetBrains

No responses yet