I have developed a struct that generates random data for testing purposes in my app but only does so if the Realm database is empty. The service class responsible for CRUD operations returns outcomes / results as RxSwift Observables.
Generating new data is predicated on the contents of the Realm - using guard
is the logical choice but requires adding a new method to the service that returns Int
rather than an Observable
which seems to be an unnecessary duplication of code and somewhat inconsistent.
i.e.
class Service {
let realm = try! Realm()
...
// Existing reactive code
func patients() -> Observable<Result<Patient>> {
let results = realm.objects(Patient.self)
return Observable.collection(from: results)
}
func objectCount() -> Int {
let realm = try! Realm()
return realm.objects(Patient.self).count
}
}
struct DataGenerator() {
...
func createRandomPatients() {
let service = Service()
guard service.objectCount() == 0 else { return }
...
//go on to generate patients
The only way I can figure to replicate this control flow using the reactive service method is to bind the Observable
to a Variable
i.e.
... service code as above ...
func createRandomPatients() {
let isEmpty = Variable<Bool>(false)
service.patients().map{ $0 == 0 }.bind(to: isEmpty)
guard isEmpty.value else { return }
// etc
It seems like a bit of a fudge as it perhaps isn't quite as clear, but it avoids adding code to the service class that won't be used in the production app. Is this bad practice or just personal preference? I'm open to alternative solutions if anyone has one...