Still a bit new to Kotlin and coroutines, so I want to learn best practices. The following code seems to work as expected in it's original context, though the naming has been tweaked here. The list of widgets is retrieved from the database, and the UI is updated correctly.
My main question is, in updateList is it approprate to use withContext (Dispatchers.Main) to access the UI from a job on the IO context? Feels a bit kludgy at first blush, but it does seem to work as expected.
class WidgetListActivity : AppCompatActivity() {
private lateinit var db: AppDatabase
private lateinit var getListJob: Job
private lateinit var widgetList: List<WidgetRecord>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_widget_list)
runBlocking {
db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "Widget.db")
.createFromAsset("database/prepop_db.sqlite").build()
}
val recyclerView = findViewById<RecyclerView>(R.id.widget_recycler_view)
val linearLayoutManager = LinearLayoutManager(this.applicationContext)
recyclerView.layoutManager = linearLayoutManager
updateList()
}
private fun updateList() {
getListJob = GlobalScope.launch (Dispatchers.IO) {
widgetList = db.widgetDao().getAllWidgets()
// HERE'S THE SECTION IN QUESTION
withContext(Dispatchers.Main) {
val recyclerView = findViewById<RecyclerView>(R.id.deck_recycler_view)
var widgetListAdapter = WidgetListAdapter(widgetList)
recyclerView.adapter = widgetListAdapter
widgetListAdapter.notifyDataSetChanged()
}
}
}
override fun onDestroy() {
runBlocking {
getListJob.join()
}
// PLEASE NOTE: I know you wouldn't normally destroy the database
// like this. The whole point of this Activity is simply to test
// loading and displaying the contents of a prepopulated database.
this.applicationContext.deleteDatabase("Widgets.db")
super.onDestroy()
}
}