พยายามเขียนแอนะล็อก `coroutine` สำหรับ `handler` แต่ไม่ได้ผล

ฉันเป็นคนใหม่ใน coroutines ตอนนี้ฉันมาดูวิธีใช้ coroutines แทนตัวจัดการ

รหัสตัวจัดการ:

fun Handler.repostDelayed(func: Runnable, delay: Long) {
removeCallbacksAndMessages(null)
postDelayed(func, delay)
}

อะนาล็อกใน Coroutines

inline fun AppCompatActivity.repostDelayed(crossinline func: () -> Unit, delay: Long) {
    lifecycleScope.cancel()
    lifecycleScope.launch {
        delay(delay)  //debounce timeOut
        func()
    }
}

แต่มันไม่ทำงาน คุณช่วยแก้ไขการแสดงออกของ Coroutines ของฉันได้ไหม?


person Serg Burlaka    schedule 21.02.2020    source แหล่งที่มา
comment
คุณไม่สามารถยกเลิกขอบเขตโครูทีนแล้วหวังว่าจะใช้มันต่อไปได้ คุณสามารถแก้ไขได้โดยการยกเลิกงานนั้นแทน แต่มันจะยังคงเป็นโค้ดที่มีชีวิตชีวา   -  person Marko Topolnik    schedule 21.02.2020


คำตอบ (1)


ฉันพบวิธีแก้ปัญหาแล้วที่นี่ และเพิ่งแก้ไขเล็กน้อย:

 fun <T, V> CoroutineScope.debounce(
    waitMs: Long = 300L,
    destinationFunction: T.(V) -> Unit
): T.(V) -> Unit {
    var debounceJob: Job? = null
    return { param: V ->
        debounceJob?.cancel()
        debounceJob = launch {
            delay(waitMs)
            destinationFunction(param)
        }
    }
}

การใช้งาน:

 private val delayFun: String.(Boolean) -> Unit = lifecycleScope.debounce(START_DELAY) {
        if(it){
            print(this)
        }
    }

     //call function
     "Hello world!".delayFun(true)

ประโยชน์ของการใช้ coroutine คือคุณไม่จำเป็นต้องยกเลิก coroutine เมื่อดู onDesstroy เนื่องจากทำงานโดยอัตโนมัติ! แต่สำหรับผู้ดูแลต้องโทร removeCallbacksAndMessages onDestroy

person Serg Burlaka    schedule 21.02.2020