AutoReloadHandler.kt (1495B) - raw
1 package me.rhunk.snapenhance.scripting 2 3 import android.net.Uri 4 import androidx.documentfile.provider.DocumentFile 5 import kotlinx.coroutines.CoroutineScope 6 import kotlinx.coroutines.Dispatchers 7 import kotlinx.coroutines.delay 8 import kotlinx.coroutines.launch 9 10 class AutoReloadHandler( 11 private val coroutineScope: CoroutineScope, 12 private val onReload: (DocumentFile) -> Unit, 13 ) { 14 private val files = mutableListOf<DocumentFile>() 15 private val lastModifiedMap = mutableMapOf<Uri, Long>() 16 17 fun addFile(file: DocumentFile) { 18 synchronized(lastModifiedMap) { 19 files.add(file) 20 lastModifiedMap[file.uri] = file.lastModified() 21 } 22 } 23 24 fun start() { 25 coroutineScope.launch(Dispatchers.IO) { 26 while (true) { 27 synchronized(lastModifiedMap) { 28 files.forEach { file -> 29 val lastModified = lastModifiedMap[file.uri] ?: return@forEach 30 runCatching { 31 val newLastModified = file.lastModified() 32 if (newLastModified > lastModified) { 33 lastModifiedMap[file.uri] = newLastModified 34 onReload(file) 35 } 36 }.onFailure { 37 it.printStackTrace() 38 } 39 } 40 } 41 delay(1000) 42 } 43 } 44 } 45 }