Hi there! I'm just starting with Coroutines in An...
# coroutines
p
Hi there! I'm just starting with Coroutines in Android and I don't even get Coroutines 101. Could someone please translate this simple Android snippet to Coroutines removing the callbacks? That would help me massively.
Copy code
StuffRepo.kt
 
stuffDS.loadStuff (object: LoadStuffCallbacks {
    override fun onSuccess(stuff : Stuff) {
        // stuff ready
    }

    override fun onError() {
        // error handling
    }
})
Copy code
StuffDS.kt

fun loadStuff(callbacks : LoadStuffCallbacks) {
    val stuff = dao.loadStuff()
    if (stuff != null) callbacks.onSuccess(stuff)
    else callbacks.onError()
}

interface LoadStuffCallbacks {
    fun onSuccess(stuff : Stuff)
    fun onError()
}
I'm trying to replicate exactly same behaviour eliminating completely the callbacks. Is it possible to do it? What's the cleanest way of doing this? Thanks a lot!
d
p
Hi there, Thanks for replying. I want to get rid of callbacks, I don't want to wrap them. Why would I want to wrap them? Makes the code uglier and more difficult to read. I though one of the main aims of coroutines is getting rid of callbacks, and I'd expect doing something like the snippet above with coroutines would be trivial, but It's challenging for me understanding how to do it (and how to do it in a way that is shorter and cleaner that the callbacks base snippet above). I hope something show me the way! Thanks
d
The idea is to wrap them once on the client end (even an extension function would do), and then use the
suspend fun
everywhere without any of those callbacks... you should really read the coroutine guide and understand the basics... also Roman put out a few articles in #feed recently... (look back in the history of that channel).
p
Oh I think I got you. Thanks for that