GlobalSnapshotManager.kt 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /*
  2. * Copyright (c) Milan Jurkulák 2024.
  3. * Contact:
  4. * e: mimoccc@gmail.com
  5. * e: mj@mjdev.org
  6. * w: https://mjdev.org
  7. */
  8. package eu.mjdev.desktop.helpers.application.base
  9. import java.util.concurrent.atomic.AtomicLong
  10. import androidx.compose.runtime.snapshots.Snapshot
  11. import kotlinx.coroutines.CoroutineDispatcher
  12. import kotlinx.coroutines.CoroutineScope
  13. import kotlinx.coroutines.channels.Channel
  14. import kotlinx.coroutines.channels.consumeEach
  15. import kotlinx.coroutines.launch
  16. import org.jetbrains.skiko.MainUIDispatcher
  17. val GlobalSnapshotManagerDispatcher: CoroutineDispatcher = MainUIDispatcher
  18. object GlobalSnapshotManager {
  19. private val started = AtomicLong(0)
  20. private val sent = AtomicLong(0)
  21. fun ensureStarted() {
  22. if (started.compareAndSet(0, 1)) {
  23. val channel = Channel<Unit>(1)
  24. CoroutineScope(GlobalSnapshotManagerDispatcher).launch {
  25. channel.consumeEach {
  26. sent.compareAndSet(1, 0)
  27. Snapshot.sendApplyNotifications()
  28. }
  29. }
  30. Snapshot.registerGlobalWriteObserver {
  31. if (sent.compareAndSet(0, 1)) {
  32. channel.trySend(Unit)
  33. }
  34. }
  35. }
  36. }
  37. }