Clean way to deal with threading issues going from Realm to lazy AnyPublisher

My goal is to lazily create a publisher of [Membership]. I want to use realm to implement the logic of when the collection updates, but I don’t want to expose Realm API in the interface. I want tom app to Combine publisher and my own model object.

My code for this below seems to work, but I wonder if there might be a simpler/cleaner way to do it:

public lazy var memberships: AnyPublisher<[Membership], Never> = {
    Just(())
        .receive(on: DispatchQueue.main)
        .flatMapLatest { _ in
            try! Realm()
                .objects(MembershipObject.self)
                .collectionPublisher
                .map { $0.map { Membership(managedObject: $0) }}
                .assertNoFailure()
        }
        .share(replay: 1)
        .eraseToAnyPublisher()

Here’s the version that I wanted to write:

public lazy var memberships: AnyPublisher<[Membership], Never> = {
    try! Realm()
        .objects(MembershipObject.self)
        .collectionPublisher
        .map { $0.map { Membership(managedObject: $0) }}
        .assertNoFailure()
        .share(replay: 1)
        .eraseToAnyPublisher()
}

But I ran into threading issues related to the fact that collectionPublisher requires a run loop, but the calling thread might not have one.

My general question… (I’ve just started using realm) How can I do this better? And in particular is there a better way to deal with threading issues then to just process everything on main as I’m doing in first working example?

Thanks,
Jesse

Welcome @Jesse_Grosjean - I’d probably take a look at our SwiftUI and Combine quickstart here:

You’ll probably want to freeze the results and pass it to the publisher. We’ve actually did a meetup presentation on this topic here -

We’ve been running a series on SwiftUI and Realm at our user group - sign up here to get notified of future events -