Calling callbacks

Here, we're calling CallBack<> from MainActivity. This callback response comes from a server or offline requests. This means returning the result of a long-running function at a later moment in time.

Check the MainActivity.kt code to use the CallBack function and handle the result:

class MainActivity : AppCompatActivity() {

var username: String = "sunnat629"
var password: String = "password"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val githubService: UserService = UserServiceImpl().getGithubServiceImpl(username,password)

val call: Call<List<UserModel>> = githubService.getUserList()
call.enqueue(object: Callback<List<UserModel>> {
override fun onFailure(call: Call<List<UserModel>>, t: Throwable) {
Log.wtf("PACKTPUB", t.message)
}

override fun onResponse(call: Call<List<UserModel>>, response: Response<List<UserModel>>) {
val adapter = UserListAdapter(this@MainActivity, response.body())
displayList.adapter = adapter
}
})
}
}

Let's discuss the preceding code as follows:

  1. First, we need to initialize UserServiceImpl().getGithubServiceImpl(username,password) so that we can call getUserList() from UserService.
  2. Then we'll call enqueue(retrofit2.Callback<T>)which will be executed asynchronously, send the request, and get the response.
  3. enqueue() has two functions: onResponse() and onFailure(). If there are any server-related errors, it will call onFailure()and if it gets the response and the resources, it will call onResponse(). We can also use the resource of the onResponse() function.

Here, we'll get a response of the UserModel list. We can show the list in our application UI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.111.87