Skip to content

Performing database operations in background thread

Devrath edited this page Jun 11, 2021 · 2 revisions

Need of using a background thread

  • Database query operations take a long time to perform the background operations.
  • There is the possibility that during this time UI thread may freeze and possibly it might crash.

Support for threading in Room

  • We can perform the operations by manually creating a separate thread. But co-routines are supported by the room that offers to thread.
  • We just add the suspend keyword and the threading is handled by room

Support for Flow API

  • Flow is an observable API.
  • When we update the table in the database. We get a new list once the database updated.
  • It is a kind of observable design pattern.
  • Basically it has two parts.
    • Flow -> Producer Side.
    • Flow Collector -> Consumer Side.
  • Ex: consider we have a list of students in the database. We will add a new entry to the database. We don't need to fetch a new list of students, Flow enables us to perform this automatically.