'Restart Firebase observe

I created a method where I fetch all the published Books in Firebase. Each Book object stores a userId string value. I would like to fetch all books excluding currentUser books. I fetch 5 books every time I call the method starting from lastBookId, however if a user publishes more than 5 books, and are the first five, they can not be shown and as a result can not continue fetching them. I was thinking about increasing the limit value and calling the query observation again.

My code:

public func fetchBooksStarting(with lastBookId: String? = nil, completion: @escaping (Result<[Book], Error>) -> Void) {

        var limit: UInt = 5

        var books = [Book]()

        let group = DispatchGroup()

        var query = database.child("books").queryOrdered(byChild: "type")

        if lastBookId != nil {
            query = query.queryStarting(afterValue: BookType.Fiction.rawValue, childKey: lastBookId)
        } else {
            query = query.queryEqual(toValue: BookType.Fiction.rawValue)
        }
        
        query.queryLimited(toFirst: limit).observeSingleEvent(of: .value, with: { snap in

            guard let snapshot = snap.children.allObjects as? [DataSnapshot] else {
                completion(.failure(DatabaseErrors.failedToFetch))
                return
            }

            books.removeAll()
            for data in snapshot {
                group.enter()

                if let dict = data.value as? [String: AnyObject] {
                    
                    let book = Book(dict: dict, bookId: data.key)
                    
                    if book.userId == currentUserUid {
                        limit += 1
                        // recall query observe
                    } else {
                        books.append(book)
                    }
                }
                
                group.leave()
            }

            group.notify(queue: .main) {
                completion(.success(books))
            }

        }, withCancel: nil)
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source