OwnedPlayerSurface.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurface.kt
1package eu.friedcutlet.yokan.ui.screens.player23import androidx.compose.runtime.*4import eu.friedcutlet.yokan.services.media.player.PlayerSurfaceResources5import kotlinx.coroutines.CompletableDeferred6import kotlinx.coroutines.yield7import kotlin.coroutines.CoroutineContext89/** Capture allocation before publication, then detach the platform view before native disposal. */10internal class OwnedPlayerSurface<T : Any>(11 registry: PlayerSurfaceResources,12 context: CoroutineContext,13 private val dispose: suspend (T) -> Unit,14) {15 var state by mutableStateOf<T?>(null)16 private set17 private var allocated: T? = null18 private var mounted = false19 private val detached = CompletableDeferred<Unit>()20 val resource = registry.register(context) {21 state = null22 if (mounted) detached.await()23 // Complete the Compose apply/disposal pass before calling native release.24 yield()25 allocated?.let { dispose(it) }26 allocated = null27 }28 suspend fun initialize(factory: () -> T) {29 resource?.runOwned { current ->30 allocated = factory()31 current()32 state = allocated33 }34 }35 fun mounted() { mounted = true }36 fun detached() { mounted = false; detached.complete(Unit) }37 fun retire() { resource?.retire() }38}3940@Composable41internal fun <T : Any> OwnedPlayerSurfaceContent(42 registry: PlayerSurfaceResources,43 factory: () -> T,44 dispose: suspend (T) -> Unit,45 content: @Composable (T, PlayerSurfaceResources.Resource) -> Unit,46) {47 val scope = rememberCoroutineScope()48 val surface = remember(registry) { OwnedPlayerSurface(registry, scope.coroutineContext, dispose) }49 DisposableEffect(surface) { onDispose { surface.retire() } }50 LaunchedEffect(surface) { surface.initialize(factory) }51 val state = surface.state52 val resource = surface.resource53 if (state != null && resource != null) {54 key(surface, state) {55 // Compose forgets effects in reverse order: acknowledge after child disposal.56 DisposableEffect(surface, state) {57 surface.mounted()58 onDispose { surface.detached() }59 }60 content(state, resource)61 }62 }63}64