본문 바로가기
Android/Kotlin

[Android] Compose 다중 이벤트 방지

by DnaJ 2023. 7. 24.
반응형

Compose 를 사용하다보면 버튼을 클릭했을때 중복 이벤트가 발생하는 것을 막아야 할 때가 있다.

 

 

처음 이벤트만 통과시키고 특정 시간동안 이벤트를 무시한다.

 

처음 이벤트가 발생 후 다른 이벤트가 연속적으로 발생하면

연속적으로 이벤트가 들어오지 않을때까지 이벤트를 무시한다.

 

package com.danchoo.utils.common


fun (() -> Unit).throttleFirst(time: Long = 200L) {
    MultipleEventPrevention.processEvent(time) { this() }
}

fun <T> ((T) -> Unit).throttleFirst(value: T, time: Long = 200L) {
    MultipleEventPrevention.processEvent(time) { this(value) }
}

object MultipleEventPrevention {
    private val now: Long
        get() = System.currentTimeMillis()

    private var lastEventTime: Long = 0

    fun processEvent(time: Long, event: () -> Unit) {
        if (now - lastEventTime >= time) {
            event.invoke()
        }

        lastEventTime = now
    }
}

 

 

https://smartstore.naver.com/happysiso

 

해피시소마켓 : 네이버쇼핑 스마트스토어

SISO

smartstore.naver.com

 

 

사용방법

@Composable
fun TestComposable(
    modifier: Modifier = Modifier,
    onClick: () -> Unit
) {

   Button(
       modifier = modifier,
       onClick = {  onClick.debounce() }
   ) {

   }
}
반응형

댓글