Can't find certain objects in my realm?


Sorry, my subject isn’t very specific.

I’m dealing with managing multiple users in my realm and having some problems. I have a user register with their email and name, then when realm logs in and creates a SyncUser, I create a new YpbUser object with the email, name, and SyncUser.current.identity in

When a user logs in, I want to use their email to look up whether there’s an existing YpbUser for their email. I’m doing it this way so in the future if someone uses username/password and then uses Google auth (not yet implemented), those SyncUsers can get to the same YpbUser.

Below is my code for checking for an existing YpbUser, along with my realm setup code. The problem I’m having is that it usually, but not always, fails to find a YpbUser even if that user exists (I’m looking at the YpbUser list in realm studio and the user with that email is definitely there!)

Inspecting from within existingUser(for:in:), users is usually 0, but it sometimes non-zero.

I assume the issue lies somewhere in the fact that I’m pretty much just guessing on how to use SyncSubscription.observe.

Please help?

fileprivate func openRealmWithUser(user: SyncUser) {
		DispatchQueue.main.async { [weak self] in
			let config = user.configuration(realmURL: RealmConstants.realmURL, fullSynchronization: false, enableSSLValidation: true, urlPrefix: nil)
			self?.realm = try! Realm(configuration: config)
			let songSub = self?.realm?.objects(Song.self).subscribe()
			let usersSub = self?.realm?.objects(YpbUser.self).subscribe()
			self?.usersToken = usersSub?.observe(\.state, options: .initial) { state in
				if !(self?! {
					self?.findYpbUser(in: (self?.realm)!)
			self?.performSegue(withIdentifier: Storyboard.LoginToNewRequestSegue, sender: nil)
	fileprivate func findYpbUser(in realm: Realm) {
		if proposedUser != YpbUser() { // gets set from the login method
			let existingUser = YpbUser.existingUser(for: proposedUser, in: realm)
			guard existingUser == nil else { // If we find the YpbUser, set as current:
				try! realm.write {
					pr("YpbUser found: \(existingUser!)")
					YpbUser.current = existingUser }
			pr("YpbUser not found.") // i.e., SyncUser set, but no YpbUser found. i.e., creating a new YpbUser
			createNewYpbUser(for: proposedUser, in: realm)

extension YpbUser {
	class func existingUser (for proposedUser: YpbUser, in realm: Realm) -> YpbUser? {
		let users = realm.objects(YpbUser.self)
		let usersWithThisEmail = users.filter("email = %@",
		if let emailUser = usersWithThisEmail.first {
			return emailUser
		return nil