|
| 1 | +/* |
| 2 | + * Copyright 2022 New Vector Ltd |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package im.vector.app.core.utils |
| 18 | + |
| 19 | +import kotlinx.coroutines.flow.Flow |
| 20 | +import kotlinx.coroutines.flow.MutableSharedFlow |
| 21 | +import kotlinx.coroutines.flow.transform |
| 22 | +import java.util.concurrent.CopyOnWriteArraySet |
| 23 | + |
| 24 | +interface SharedEvents<out T> { |
| 25 | + fun stream(consumerId: String): Flow<T> |
| 26 | +} |
| 27 | + |
| 28 | +class EventQueue<T>(capacity: Int) : SharedEvents<T> { |
| 29 | + |
| 30 | + private val innerQueue = MutableSharedFlow<OneTimeEvent<T>>(replay = capacity) |
| 31 | + |
| 32 | + fun post(event: T) { |
| 33 | + innerQueue.tryEmit(OneTimeEvent(event)) |
| 34 | + } |
| 35 | + |
| 36 | + override fun stream(consumerId: String): Flow<T> = innerQueue.filterNotHandledBy(consumerId) |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Event designed to be delivered only once to a concrete entity, |
| 41 | + * but it can also be delivered to multiple different entities. |
| 42 | + * |
| 43 | + * Keeps track of who has already handled its content. |
| 44 | + */ |
| 45 | +private class OneTimeEvent<out T>(private val content: T) { |
| 46 | + |
| 47 | + private val handlers = CopyOnWriteArraySet<String>() |
| 48 | + |
| 49 | + /** |
| 50 | + * @param asker Used to identify, whether this "asker" has already handled this Event. |
| 51 | + * @return Event content or null if it has been already handled by asker |
| 52 | + */ |
| 53 | + fun getIfNotHandled(asker: String): T? = if (handlers.add(asker)) content else null |
| 54 | +} |
| 55 | + |
| 56 | +private fun <T> Flow<OneTimeEvent<T>>.filterNotHandledBy(consumerId: String): Flow<T> = transform { event -> |
| 57 | + event.getIfNotHandled(consumerId)?.let { emit(it) } |
| 58 | +} |
0 commit comments