https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

aiidziis

06/04/2020, 9:52 AM
Hey! Currently in MPP we are using SqlDelight and coroutines to insert data into db:
Copy code
class DbHelper(db: Db) {
    suspend fun insert(elements: List<Element>) = withContext(Dispatchers.Default) {
        db.elementQueries.transaction {
            db.elementQueries.insert(.....)
        }
    }
}
This works fine when elements list is not too big, but now we encountered use case where we need to insert larger amount of data (in worst case insert is 1200ms), and now this same approach is causing problems on iOS because this all happens on Main Thread(async) , and while the data is inserting UI is getting blocked when user interacts with UI (scrolling). Is there a way with current coroutines versions
"1.3.5-native-mt"
to improve this? afaik with current coroutines version it is not possible move insert to Background Thread?
l

louiscad

06/04/2020, 11:21 AM
@aiidziis Yes, native-mt makes
Dispatchers.Default
be on a background thread.
a

aiidziis

06/04/2020, 11:29 AM
Hm, then I guess UI is getting blocked by something else? I have scope defined like this:
Copy code
internal class EngineScope : CoroutineScope {
    internal val job = SupervisorJob()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job
}
and I am calling this insert function:
Copy code
engineScope.launch { dbHelper.insert(elements) }
So this shouldn’t block main thread?
l

louiscad

06/04/2020, 11:32 AM
@aiidziis You can log the result of
NSThread.isMainThread
at the right place to find out. (Needs import of
import platform.Foundation.NSThread
) You might need to expect/actual it if in common code.
a

aiidziis

06/04/2020, 11:41 AM
Ok, you are right it is called on background thread and this
insert
function is not blocking UI. Will investigate further what else might be blocking it. Thanks.
k

Kris Wong

06/04/2020, 1:00 PM
is your UI trying to query at the same time the insert is happening?
a

aiidziis

06/04/2020, 1:02 PM
Turns out I wasn’t performing select from DB on
Dispatchers.Default
.
Was using
flowOn(Dispatchers.Default)
on Flow and thought that it would make
select
on
Dispatchers.Default
.
3 Views