traintrape-moi/client/utils/background.ts

43 lines
1.5 KiB
TypeScript

import * as BackgroundFetch from 'expo-background-fetch'
import * as TaskManager from 'expo-task-manager'
import { Platform } from 'react-native'
import { useEffect } from 'react'
const BACKGROUND_FETCH_TASK = "background-fetch"
const BACKGROUND_FETCH_INTERVAL = 20
async function backgroundUpdate() {
async () => {
const now = Date.now()
console.log(`Got background fetch call at date: ${new Date(now).toISOString()}`)
// Be sure to return the successful result type!
return BackgroundFetch.BackgroundFetchResult.NewData
}
}
TaskManager.defineTask(BACKGROUND_FETCH_TASK, backgroundUpdate)
export async function startBackgroundFetchService(): Promise<void | (() => void)> {
if (Platform.OS === "web") {
const interval = setInterval(backgroundUpdate, BACKGROUND_FETCH_INTERVAL)
return () => clearInterval(interval)
}
if (await TaskManager.isTaskRegisteredAsync(BACKGROUND_FETCH_TASK))
return async () => await BackgroundFetch.unregisterTaskAsync(BACKGROUND_FETCH_TASK)
await BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
minimumInterval: BACKGROUND_FETCH_INTERVAL,
stopOnTerminate: false,
startOnBoot: true,
})
return async () => await BackgroundFetch.unregisterTaskAsync(BACKGROUND_FETCH_TASK)
}
export const useStartBackgroundFetchServiceEffect = () => useEffect(() => {
let cleanup: void | (() => void) = () => {}
startBackgroundFetchService().then(result => cleanup = result)
return cleanup
}, [])