https://kotlinlang.org logo
w

Wai-Wai Ng

06/07/2023, 2:27 PM
Want to run a quick sanity check - I have a external resource which I want to only be calling once at any given time. However, occasionally the request fails, so I want to set a timeout. I'm thinking of something like
Copy code
val job: Job? = null

fun refresh() {
  if (!job?.isCompleted) return 

  job = launch {
    withTimeoutOrNull(10_000) {
      // actual code here
    }
  }
}
Is this sensible or is there a better way of doing this?
f

franztesca

06/07/2023, 2:41 PM
You can use a lazy coroutine
Copy code
class MyClass(private val scope: CoroutineScope) {
    
    private val refreshJob = scope.launch(start = CoroutineStart.LAZY) {
        // Refresh logic 
    }
    
    // True if actually starting it, false if already started
    fun refresh(): Boolean = refreshJob.start()
    
}