简体   繁体   中英

Can I shorten the room insertion time using RxJava?

I am developing an android app. I'm having a hard time writing code that adds a to-do list to a calendar. Let me show you the code first.

private fun addTodoList(entity: MyTodo) {
    val start = Calendar.getInstance()
    val end = start.clone() as Calendar
    end.time = SimpleDateFormat("MM dd, yyyy", Locale.getDefault()).parse(Date.END_OF_DAY)!!

    CoroutineScope(Dispatchers.Default).launch {
        val id = MyDatabase.getInstance(mContext).getTodoDao().insert(entity)
        val dao = MyDatabase.getInstance(mContext).getCalendarDao()

        do {
            val date = ymd.format(start.timeInMillis)
            val item = CalendarEntity(date, id.toInt())
            dao.insert(item)
            start.add(Calendar.DAY_OF_MONTH, 1)
        } while (start.timeInMillis <= end.timeInMillis)
    }
}

This is the code that inserts the Todo created by the user through TodoDao , and inserts the value into CalendarDao from today to Date.END_OF_DAY (I randomly designated this value as "December 31, 2025"). But the insertion speed through CalendarDao was quite slow. There is no inconvenience in the UI, but if the user completely terminates the app from the task during insertion, it will be terminated without inserting data until the end. It has been said that using RxJava can solve this problem, how can you solve it? Even if it's not RxJava , if there is a way to solve this problem, please let me know.

Change Dispatchers.Default to Dispatchers.IO

This is a database operation and it should be handled on an IO thread, Default is a real heavy duty CPU thread.

Using RxJava is a good way to standardize your database interactions, it allows you to stay off the UI thread and setups up an Observer pattern to allow you to react to the data as you get it instead of waiting for it.

If they close the app while this operation is happening there is not much you can do, as this is handled under 1 transaction. As such the actual changes to the database are only handled at the end, meaning if the operation doesn't complete nothing gets inserted. But you also don't want to do this 1 transaction at a time because that is extremely slow. Its a reliability vs speed question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM