KVHeavyTaskDataProviderInterface
public protocol KVHeavyTaskDataProviderInterface
Protocol defining the interface for heavy task data providers.
This protocol establishes the contract for implementing concrete data providers that execute resource-intensive operations. All data providers must implement both start and stop methods to ensure proper task lifecycle management and integration with the task manager.
Core Responsibilities
- Task Execution: Implement the actual heavy computation or I/O operation
- Progress Reporting: Publish real-time updates through the event system
- Interruption Handling: Gracefully respond to stop requests from the manager
- State Management: Maintain task state and support resumption when applicable
- Error Handling: Properly handle and report failures through the result system
Implementation Guidelines
- Thread Safety: Methods may be called from different threads; ensure proper synchronization
- Cancellation: Check for interruption periodically during long-running operations
- Resource Management: Clean up resources properly in both success and failure cases
- Event Publishing: Use customEventPublisher for progress updates, not result delivery
- Result Delivery: Call resultPublisher exactly once with the final outcome
Integration with Task Manager
The task manager handles:
- Provider instantiation and lifecycle management
- Event routing to registered observers
- Result caching and callback coordination
- Concurrency control and queue management
- Stop action processing (reuse vs dealloc)
Example Implementation Pattern
class MyHeavyTaskProvider: KVHeavyTaskBaseDataProvider<String, Data, Progress>, KVHeavyTaskDataProviderInterface {
private var isStopped = false
func start() {
// Validate input and setup
guard isValidKey(key) else {
resultPublisher(.failure(ValidationError.invalidKey))
return
}
// Execute task with progress updates
performHeavyOperation { progress in
guard !isStopped else { return }
customEventPublisher(progress)
} completion: { result in
resultPublisher(result)
}
}
func stop() -> KVHeavyTaskDataProviderStopAction {
isStopped = true
return shouldPreserveState ? .reuse : .dealloc
}
}
-
Initiates the execution of the heavy task.
This method contains the core logic for performing the resource-intensive operation. It should handle the complete task lifecycle from initialization to completion, including progress reporting and error handling.
Implementation Requirements
- Result Publishing: Must call
resultPublisher
exactly once with success or failure - Progress Updates: Should use
customEventPublisher
for real-time status updates - Interruption Handling: Must check for stop conditions periodically
- Error Management: Handle all exceptions and report through result publisher
- Resource Cleanup: Ensure proper cleanup regardless of completion method
Threading Considerations
- This method may be called from any thread
- Long-running operations should not block the calling thread
- Use appropriate queues for I/O operations and CPU-intensive work
- Publishers are thread-safe and can be called from any context
Performance Guidelines
- Minimize setup overhead for frequently created/destroyed providers
- Use efficient data structures for intermediate state
- Consider memory usage, especially for tasks that may be interrupted
- Implement appropriate cancellation points for responsive interruption
Declaration
Swift
func start()
- Result Publishing: Must call
-
Gracefully stops the currently executing task and determines cleanup strategy.
This method is called by the task manager when a higher-priority task requires resources or when the task needs to be cancelled. The implementation should stop the current operation as quickly as possible while preserving data integrity.
Return Value Significance
The returned
KVHeavyTaskDataProviderStopAction
determines what happens to this provider instance:.reuse
: Provider stays in memory and can resume later from current state.dealloc
: Provider is deallocated immediately to free memory
Implementation Guidelines
- Quick Response: Should return promptly (typically < 100ms)
- State Preservation: For
.reuse
, maintain enough state to resume effectively - Clean Shutdown: For
.dealloc
, ensure all resources are properly cleaned up - Thread Safety: Must be safe to call concurrently with
start()
- Idempotency: Safe to call multiple times without side effects
Strategy Selection Criteria
Consider returning
.reuse
when:- Task has expensive initialization or setup phase
- Intermediate results are valuable and should be preserved
- Task is likely to be resumed soon (high priority, frequent access)
- Memory usage is reasonable and won’t cause pressure
Consider returning
.dealloc
when:- Task has large memory footprint that should be freed immediately
- Task is unlikely to be resumed (low priority, infrequent access)
- Setup cost is low and re-initialization is acceptable
System is under memory pressure
Declaration
Swift
@discardableResult func stop() -> KVHeavyTaskDataProviderStopAction
Return Value
Strategy for handling this provider after stop (.reuse or .dealloc)
-
resume()
Extension method, asynchronousDefault no-op resume implementation for providers that are not resumable.
Declaration
Swift
func resume() async