package eu.friedcutlet.yokan.ui.screens.player import androidx.compose.runtime.* import eu.friedcutlet.yokan.services.media.player.PlayerSurfaceResources import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.yield import kotlin.coroutines.CoroutineContext /** Capture allocation before publication, then detach the platform view before native disposal. */ internal class OwnedPlayerSurface( registry: PlayerSurfaceResources, context: CoroutineContext, private val dispose: suspend (T) -> Unit, ) { var state by mutableStateOf(null) private set private var allocated: T? = null private var mounted = false private val detached = CompletableDeferred() val resource = registry.register(context) { state = null if (mounted) detached.await() // Complete the Compose apply/disposal pass before calling native release. yield() allocated?.let { dispose(it) } allocated = null } suspend fun initialize(factory: () -> T) { resource?.runOwned { current -> allocated = factory() current() state = allocated } } fun mounted() { mounted = true } fun detached() { mounted = false; detached.complete(Unit) } fun retire() { resource?.retire() } } @Composable internal fun OwnedPlayerSurfaceContent( registry: PlayerSurfaceResources, factory: () -> T, dispose: suspend (T) -> Unit, content: @Composable (T, PlayerSurfaceResources.Resource) -> Unit, ) { val scope = rememberCoroutineScope() val surface = remember(registry) { OwnedPlayerSurface(registry, scope.coroutineContext, dispose) } DisposableEffect(surface) { onDispose { surface.retire() } } LaunchedEffect(surface) { surface.initialize(factory) } val state = surface.state val resource = surface.resource if (state != null && resource != null) { key(surface, state) { // Compose forgets effects in reverse order: acknowledge after child disposal. DisposableEffect(surface, state) { surface.mounted() onDispose { surface.detached() } } content(state, resource) } } }