feat: ability to provide custom dispatch implementations #287
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR introduces a new
DispatchStrategyAPI that allows users to customize how database operations are dispatched to coroutine contexts. By default, operations useDispatchers.IO, but users can now provide a customCoroutineDispatcheror a fully customDispatchFunctionfor complete control over the execution context.Motivation
The primary motivation for this feature is to support the Swift Connection Pool implementation, where the pool itself handles dispatching operations. In this case, we need to bypass PowerSync's default dispatching mechanism and let the pool manage the execution context.
Implementation Details
New Types
DispatchFunction- An interface that defines how to dispatch operations:operator invoketo enable convenient syntax:dispatchFunction { ... }DispatchStrategy- A sealed class with three variants:Default: UsesDispatchers.IO(the default behavior)Dispatcher: Accepts aCoroutineDispatcherdirectlyCustom: Accepts a customDispatchFunctionfor full controlChanges
dispatchStrategyparameter (defaults toDispatchStrategy.Default) to:PowerSyncDatabase()factory functionPowerSyncDatabase.opened()PowerSyncDatabase.openInMemory()InternalDatabaseImplto accept a non-nullableDispatchStrategyand use it for all database operationsDispatchStrategy.Defaultto internally useDispatcher(Dispatchers.IO)to avoid code duplicationSwift Connection Pool Integration
The Swift Connection Pool implementation uses
DispatchStrategy.Customwith a no-op dispatch function, allowing the pool to handle dispatching:Breaking Changes
None - this is a fully backward compatible addition. The
dispatchStrategyparameter has a default value ofDispatchStrategy.Default, which maintains the existing behavior.