-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨: add new hook : useBackToFrontEffect\useFrontToBackEffect
- Loading branch information
Showing
2 changed files
with
66 additions
and
14 deletions.
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
hooks/src/main/kotlin/xyz/junerver/compose/hooks/useBackFront.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package xyz.junerver.compose.hooks | ||
|
||
import android.annotation.SuppressLint | ||
import androidx.compose.runtime.Composable | ||
import androidx.lifecycle.compose.LifecycleResumeEffect | ||
|
||
/** | ||
* Description: 进入后台**再次**回到前台时执行Effect,不同于官方 API,只在再进入时才执行。 第一次渲染(不执行)-> | ||
* 进入后台在返回(执行)。 | ||
* | ||
* Effect is executed when entering the background and returning to the | ||
* foreground. Different from the official API, it is only executed when | ||
* re-entering. | ||
* | ||
* First rendering (not executed) -> enter the background and return | ||
* (executed) | ||
* | ||
* @author Junerver date: 2024/3/14-15:10 Email: [email protected] | ||
* Version: v1.0 | ||
*/ | ||
@SuppressLint("ComposableNaming") | ||
@Composable | ||
fun useBackToFrontEffect(vararg deps: Any?, effect: () -> Unit) { | ||
val inBackgroundRef = useRef(default = false) | ||
LifecycleResumeEffect(keys = deps) { | ||
if (inBackgroundRef.current) { | ||
effect() | ||
inBackgroundRef.current = false | ||
} | ||
onPauseOrDispose { inBackgroundRef.current = true } | ||
} | ||
} | ||
|
||
/** | ||
* Use front to back effect,contrary to the [useBackToFrontEffect] | ||
* behavior, the effect is executed when the App enters the background | ||
* | ||
* @param deps | ||
* @param effect | ||
* @receiver | ||
*/ | ||
@SuppressLint("ComposableNaming") | ||
@Composable | ||
fun useFrontToBackEffect(vararg deps: Any?, effect: () -> Unit) { | ||
val inBackgroundRef = useRef(default = false) | ||
LifecycleResumeEffect(keys = deps) { | ||
if (inBackgroundRef.current) { | ||
inBackgroundRef.current = false | ||
} | ||
onPauseOrDispose { | ||
effect() | ||
inBackgroundRef.current = true | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters