All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.jetbrains.datalore.base.observable.event.MultiWaySync.kt Maven / Gradle / Ivy

There is a newer version: 4.5.3-alpha1
Show newest version
/*
 * Copyright (c) 2019. JetBrains s.r.o.
 * Use of this source code is governed by the MIT license that can be found in the LICENSE file.
 */

package jetbrains.datalore.base.observable.event

import jetbrains.datalore.base.function.Runnable
import jetbrains.datalore.base.registration.Registration

/**
 * Utility class for implementing multi-way synchronizations. It prevents infinite recursive updates
 * by using an internal flag.
 */
class MultiWaySync {
    var isInSync = false
        private set

    fun  inSync(source: EventSource): EventSource {
        return object : EventSource {
            override fun addHandler(handler: EventHandler): Registration {
                return source.addHandler(object : EventHandler {
                    override fun onEvent(event: EventT) {
                        sync(object : Runnable {
                            override fun run() {
                                handler.onEvent(event)
                            }
                        })
                    }
                })
            }
        }
    }

    private fun startSync() {
        if (isInSync) {
            throw IllegalStateException("Nested syncs aren't support")
        }
        isInSync = true
    }

    private fun finishSync() {
        if (!isInSync) {
            throw IllegalStateException("Not in sync")
        }

        isInSync = false
    }

    fun sync(action: Runnable) {
        if (isInSync) return

        startSync()
        try {
            action.run()
        } finally {
            finishSync()
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy