Retrofit and Coroutines

MVVM with Retrofit

MVVM with Retrofit

Mockapi

  • MockAPI is a simple tool that lets you easily mock up APIs, generate custom data, and preform operations on it using RESTful interface.
  • MockAPI is meant to be used as a prototyping/testing/learning tool.

Coroutines

  • Asynchronous or non-blocking programming is an important part of the development landscape.
  • When creating server-side, desktop, or mobile applications, it’s important to provide an experience that is not only fluid from the user’s perspective, but also scalable when needed.
  • Coroutines are helpful in two main problems,
    • A long-running task that can block the main thread
    • Main safetyallows you to ensure that any suspend function can be called from the main thread
  • Coroutines build upon regular functions by adding two new operations. In addition to invoke (or call) and return, coroutines add suspend and resume.
    • suspend — pause the execution of the current coroutine, saving all local variables
    • resume — continue a suspended coroutine from the place it was paused

Suspend Function

Kotlin
suspend fun getAllTask() = mainService.getAllTasks()
  • suspending function is just a regular Kotlin function with an additional suspend modifier which indicates that the function can suspend the execution of a coroutine.
  • You can only call suspend functions from other suspend functions, or by using a coroutine builder like launch to start a new coroutine.
  • We use call back functions when we get response from our Async task. Suspend and resume work together to replace callbacks.
  • To specify where the coroutines should run, Kotlin provides three dispatchers that you can use:
    • Dispatchers.Main — Use this dispatcher to run a coroutine on the main Android thread. This should be used only for interacting with the UI and performing quick work. Examples include calling suspend functions, running Android UI framework operations, and updating LiveData objects.
    • Dispatchers.IO — This dispatcher is optimized to perform disk or network I/O outside of the main thread. Examples include using the Room component, reading from or writing to files, and running any network operations.
    • Dispatchers.Default — This dispatcher is optimized to perform CPU-intensive work outside of the main thread. Example use cases include sorting a list and parsing JSON.
  • Example
Kotlin
CoroutineScope(Dispatchers.IO + exceptionHandler).launch {
            val response = mainRepository.getAllTask()
}
  • When we call getAllTask() suspend method, then it suspends our coroutine. The coroutine on the main thread will be resumed with the result as soon as the withContext block is complete.

📢 Using suspend doesn’t tell Kotlin to run a function on a background thread. It’s normal for suspend functions to operate on the main thread.

Retrofit

  • Retrofit is a type-safe HTTP client for Android and Java.

Github Repository