Attempt fix #401

This commit is contained in:
vfsfitvnm
2022-10-26 13:08:45 +02:00
parent f4a55ff2ad
commit ed8eb7cf8a
64 changed files with 373 additions and 944 deletions

1
compose-persist/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

View File

@@ -0,0 +1,46 @@
plugins {
id("com.android.library")
kotlin("android")
}
android {
namespace = "it.vfsfitvnm.compose.persist"
compileSdk = 33
defaultConfig {
minSdk = 21
targetSdk = 33
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"))
}
}
sourceSets.all {
kotlin.srcDir("src/$name/kotlin")
}
buildFeatures {
compose = true
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
composeOptions {
kotlinCompilerExtensionVersion = libs.versions.compose.compiler.get()
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation(libs.compose.foundation)
}

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest>
</manifest>

View File

@@ -0,0 +1,26 @@
package it.vfsfitvnm.compose.persist
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
@Suppress("UNCHECKED_CAST")
@Composable
fun <T> persist(tag: String, initialValue: T): MutableState<T> {
val context = LocalContext.current
return remember {
context.persistMap?.getOrPut(tag) { mutableStateOf(initialValue) } as? MutableState<T>
?: mutableStateOf(initialValue)
}
}
@Composable
fun <T> persistList(tag: String): MutableState<List<T>> =
persist(tag = tag, initialValue = emptyList())
@Composable
fun <T : Any?> persist(tag: String): MutableState<T?> =
persist(tag = tag, initialValue = null)

View File

@@ -0,0 +1,3 @@
package it.vfsfitvnm.compose.persist
typealias PersistMap = HashMap<String, Any?>

View File

@@ -0,0 +1,19 @@
package it.vfsfitvnm.compose.persist
import android.app.Activity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.platform.LocalContext
@Composable
fun PersistMapCleanup(tagPrefix: String) {
val context = LocalContext.current
DisposableEffect(context) {
onDispose {
if (context.findOwner<Activity>()?.isChangingConfigurations == false) {
context.persistMap?.keys?.removeAll { it.startsWith(tagPrefix) }
}
}
}
}

View File

@@ -0,0 +1,5 @@
package it.vfsfitvnm.compose.persist
interface PersistMapOwner {
val persistMap: PersistMap
}

View File

@@ -0,0 +1,16 @@
package it.vfsfitvnm.compose.persist
import android.content.Context
import android.content.ContextWrapper
val Context.persistMap: PersistMap?
get() = findOwner<PersistMapOwner>()?.persistMap
internal inline fun <reified T> Context.findOwner(): T? {
var context = this
while (context is ContextWrapper) {
if (context is T) return context
context = context.baseContext
}
return null
}