How to Define Callbacks in Android?

Viewed 254414

During the most recent Google IO, there was a presentation about implementing restful client applications. Unfortunately, it was only a high level discussion with no source code of the implementation.

In this diagram, on the return path there are various different callbacks to other methods.

google io presentation slide

How do I declare what these methods are?

I understand the idea of a callback - a piece of code that gets called after a certain event has happened, but I don't know how to implement it. The only way I've implemented callbacks so far have been overriding various methods (onActivityResult for example).

I feel like I have a basic understanding of the design pattern, but I keep on getting tripped up on how to handle the return path.

7 Answers

asume the main function is the activity that is triggering the event:

fun main() {

val worker = Worker()

worker.setOnCallListener(
    object: OnCallListener {
        override fun onCall() {
            // here we define what should happen
            // when the event accures
            print("event happend")
        }
    }
)

// most events will be called from Android system itself
// but in our case we have to call it manually
worker.listener.onCall()
}

the Worker class has an instance of Type OnCallListener interface and a method to set its value:

class Worker() {
    lateinit var listener: OnCallListener

    fun setOnCallListener(listener: OnCallListener) {
        this.listener = listener
    }
}

and the OnCallListener interface looks like this:

interface OnCallListener {
    fun onCall()
}
Related