nerdsupremacist / Graphaello

A Tool for Writing Declarative, Type-Safe and Data-Driven Applications in SwiftUI using GraphQL

Home Page:https://graphaello.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Polling

dyedgreen opened this issue · comments

I was looking at this, and was wondering if there currently is a way to poll a query every N seconds? (E.g. if I display a set of comments, I might want to refresh the view every few seconds such that people are always up-to-date.)

Yes! There is a way to refresh the content. However, I haven't built in any functionality like refreshing every N seconds.

You can get a QueryRefreshController from the Environment. This object lets you ask for a refresh. So your case could be covered by something like this (warning! I haven't tested this implementation. I just guess that it will work)

struct ContentView: View {
    @Environment(\.queryRefreshController)
    var refreshController

    @State
    private var timer: Timer?

    var body: some View {
        VStack {
            ....
        }
        .onAppear {
            DispatchQueue.main.async {
                self.timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { _ in
                    self.refreshController?.refresh()
                }
            }
        }
        .onDisappear {
            self.timer?.invalidate()
        }
    }

But I would be into the idea of adding a kind of RefreshPolicy modifier to views that are rendering data from GraphQL. Such a RefreshPolicy could decide in which scenarios to refresh (are there any errors? has a mutation occurred?) and to schedule future refreshes.

let api = MyAPI()
let content = api
    .content()
    .refreshPolicy(Polling(every: .seconds(20))

Yes, that’s sounds really useful! Especially refreshing on mutations of a given field is super good, since that means I can subscribe to updates whenever they happen anywhere in the app 😍