How can I mix these two classes in an observable t...
# android
a
How can I mix these two classes in an observable that handles both normal and one time observation without rewriting the logic? In other words, how can I create a class that somehow extends these two?
Copy code
open class OneTimeObservable {
    private var isInitialised = false
    var state = false
        set(value) {
            field = value
            isInitialised = true
            if (oneTimeObservers.isNotEmpty()) {
                notifyOneTimeObservers(value)
            }
        }

    private val oneTimeObservers = mutableMapOf<String, (Boolean) -> Unit>()

    fun whenReady(tag: String, listener: (Boolean) -> Unit): Boolean {
        return if (!isInitialised) {
            oneTimeObservers[tag] = listener
            false
        } else {
            listener(state)
            true
        }
    }

    private fun notifyOneTimeObservers(boolean: Boolean) {
        oneTimeObservers.forEach {
            it.value(boolean)
        }
        oneTimeObservers.clear()
    }
}

open class Observable {
    var state = false
        set(value) {
            field = value
            notifyObservers(value)
        }

    private val observers = mutableMapOf<String, (Boolean) -> Unit>()

    fun addObserver(tag: String, observer: (Boolean) -> Unit) {
        observers[tag] = observer
    }

    private fun notifyObservers(boolean: Boolean) {
        observers.forEach {
            it.value(boolean)
        }
    }
}
i
isn't it better to use an interface and implements it within your two classes?
a
The thing is, I want to keep the function names of whenReady() and addObservers() to make code reading easier when I am using an observable. And then I want to create a third observable that supports both normal and one time observation. The only solution I see is: create 3 interfaces, the first for the state, the second for the one time observable, and the third for normal observable. Each of those two classes implement the state and the appropriate observable. And the mixed observable class implement all the 3 interfaces. But is there a better solution? 3 interfaces for adding a class is too much I guess. What do you think?