Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Couchbase in background thread

I am developing an app which uses Couchbase to sync the documents. Right now all the documents I am creating on main thread and using the same.

But now I got stuck in a scenario where I need to create and push the document in some other thread than main, not blocking the UI.

How I can run the part of Couchbase database in background thread to support only above scenario.

Tried the methods in the Couchbase documentation for concurrency support.But receiving the thread safety crash crash telling whenever I create documents in the background thread like this.

DispatchQueue.global(qos: .background).async {
   //creating couchbase documents here
}

Getting below crash:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '***** THREAD-SAFETY VIOLATION: This database is being used on a thread it wasn't created on! Please see the concurrency guidelines in the Couchbase Lite documentation. *****

Please help.

like image 494
Shyam Avatar asked Mar 20 '18 11:03

Shyam


1 Answers

Couchbase Lite APIs in 1.x are not thread safe and support a thread confinement model. So you cannot share objects across threads - In other words, if you created a CBLDatabase object on main thread, you cannot use that instance on your background thread. You will have to create a new instance for your background thread. So do the following :

  • Create a new serial dispatch queue
  • Create a CBLManager instance
  • Set the manager’s dispatchQueue property to the queue you created
  • Do your Couchbase Lite calls inside dispatch_async calls on your queue.

As an aside, Couchbase Mobile 2.0 APIs are thread safe and something you may want to consider if this is a greenfield project.

like image 154
rajagp Avatar answered Oct 23 '22 04:10

rajagp