I have a simple non-reactive function that I'd like to run on a SerialDispatchQueueScheduler
. The method doesn't return anything neither I require it to emit any events but it has to be run on a scheduler
func deleteDataOf(_ personId: Int, on scheduler: SerialDispatchQueueScheduler) {
//Run the method body on scheduler
try? removeItem(at: getDirectoryURL(personId: personId))
}
The simplest solution is to put your side effect in a .do(onNext:)
, or .subscribe(onNext:)
operator that is invoked on the scheduler in question. That way it's part of the observable chain.
The next simplest is to schedule the operation on the scheduler:
func deleteDataOf(_ personId: Int, on scheduler: SchedulerType) -> Disposable {
scheduler.schedule(()) {
try? removeItem(at: getDirectoryURL(personId: personId))
return Disposables.create()
}
}
Note that it returns a Disposable for possible cancelation.
I notice that your side effect throws, which implies to me that you are potentially interested in errors. Maybe a Completable would be a better idea, but then you would have to subscribe to the result.
Something like this:
func deleteDataOf(_ personId: Int) -> Completable {
Completable.deferred {
do {
try removeItem(at: getDirectoryURL(personId: personId))
return .empty()
}
catch {
return .error(error)
}
}
}
func deleteDataOf(_ personId: Int, on scheduler: SchedulerType) {
_ = deleteDataOf(personId)
.subscribeOn(scheduler)
.subscribe(onError: { print("there was an error", $0) })
}