Skip to content

Instantly share code, notes, and snippets.

@League2EB
Created June 4, 2020 03:40
Show Gist options
  • Save League2EB/5f1f0091f68895a25abed9790984e0c6 to your computer and use it in GitHub Desktop.
Save League2EB/5f1f0091f68895a25abed9790984e0c6 to your computer and use it in GitHub Desktop.
RealmSwift + Rx
func delete<T>(type: T.Type, code: String) -> Observable<()> where T: Object {
return Observable.create { observer in
do {
let realm = try Realm()
guard let object = realm.objects(type).filter(code).first else { return Disposables.create() }
realm.delete(object)
observer.onNext(())
observer.onCompleted()
} catch let error {
observer.onError(error)
}
return Disposables.create()
}
}
@Slowhand0309
Copy link

Slowhand0309 commented Jun 4, 2020

@League2EB

thanks for your questions.
I think the first thing to do is to specify a T: Object and prepare a deletable method.
Next I thought it would be good to create a method if you want to filter by items other than keys

example)

    static func delete<T>(element: T) -> Observable<()> where T: Object {
        return Observable.create { observer in
            do {
                let realm = try Realm()
                try realm.write {
                    realm.delete(element)
                    observer.onNext(())
                    observer.onCompleted()
                }
            } catch let error {
                observer.onError(error)
            }
            return Disposables.create()
        }
    }
    static func deleteBy<T>(element: T, code: String) -> Observable<()> where T : Object {
        return Realm.query(type: T.self, formattedString: NSPredicate(format: "code == %@", argumentArray: [code]))
            .flatMap { Realm.delete(element: $0) }
    }

(* I have not actually operated it)
Thank you!

@League2EB
Copy link
Author

@Slowhand0309
Thx all !
台日友好

@Slowhand0309
Copy link

👍

@Slowhand0309
Copy link

@League2EB
I fixed it so that it compiles!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment