Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

android - When i use delay should i switch to Default or IO thread from main thread

Sometimes my fragment scope needs to wait before executes some view stuffs. In these cases i am adding delay(ms) function into my scope. But my scope initialized with the Dispathers.Main . I know unlike Thread.sleep(ms), delay(ms) is not blocking current thread. Should i consider which thread executes delay function ?

val scope = CoroutineScope(Dispatchers.Main)
        scope.launch {
            //do i really need to switch IO
            withContext(Dispatchers.IO) {
                delay(4000)
            }
            someUIStuff()
        }
    }
question from:https://stackoverflow.com/questions/65932364/when-i-use-delay-should-i-switch-to-default-or-io-thread-from-main-thread

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No need to switch, delay is a suspend function, it will suspend the current Coroutinescope not the executing Thread. As per documentation of delay function, check the first point

/**
 * Delays coroutine for a given time without blocking a thread and resumes it after a specified time.
 * This suspending function is cancellable.
 * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
 * immediately resumes with [CancellationException].
 *
 * Note that delay can be used in [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
 *
 * Implementation note: how exactly time is tracked is an implementation detail of [CoroutineDispatcher] in the context.
 * @param timeMillis time in milliseconds.
 */
public suspend fun delay(timeMillis: Long) {
    if (timeMillis <= 0) return // don't delay
    return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> ->
        cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...