WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Intermediate · question 36 of 100

Explain the purpose of the suspend keyword in Kotlin, and provide a use case.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

The ‘suspend‘ keyword in Kotlin is used to mark functions that can be potentially long-running and can suspend the execution of a coroutine without blocking the thread.

When a function is marked with ‘suspend‘, it can be thought of as a coroutine, which means it can yield its execution to the calling coroutine, allowing other routines to run while it’s waiting for an operation to complete, such as a network request, file I/O, or database query.

A practical use case where ‘suspend‘ functions can be useful in Android app development is when working with ‘Room‘, which is an Android library used to handle database operations. When working with ‘Room‘, calling database operations on the main thread can cause the app UI to freeze and become unresponsive, which is not desirable.

To avoid this, ‘Room‘ provides a way to run database operations asynchronously by using coroutines and marking database access functions with the ‘suspend‘ keyword. An example of such a function is:

@Dao
interface UserDao {
  @Query("SELECT * FROM user WHERE uid = :id LIMIT 1")
  suspend fun getUserById(id: Int): User
}

In the above example, the ‘getUserById()‘ function is marked as ‘suspend‘ because it fetches data from the database, which can take some time to complete. By marking the function as ‘suspend‘, the calling coroutine can be suspended while the database operation is being executed, allowing other routines to run in the meantime.

In summary, the ‘suspend‘ keyword in Kotlin is used to mark functions that can be potentially long-running and can suspend the execution of a coroutine without blocking the thread, making it useful for asynchronous operations such as network requests or database queries.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics