|
| 1 | +package com.bumble.appyx.interop.rx3.connectable |
| 2 | + |
| 3 | +import androidx.lifecycle.Lifecycle |
| 4 | +import com.bumble.appyx.core.lifecycle.subscribe |
| 5 | +import com.jakewharton.rxrelay3.PublishRelay |
| 6 | +import com.jakewharton.rxrelay3.Relay |
| 7 | +import io.reactivex.rxjava3.core.Observer |
| 8 | + |
| 9 | +class NodeConnector<Input, Output : Any>( |
| 10 | + override val input: Relay<Input> = PublishRelay.create(), |
| 11 | +) : Connectable<Input, Output> { |
| 12 | + |
| 13 | + private val intake: Relay<Output> = PublishRelay.create() |
| 14 | + private val exhaust: Relay<Output> = PublishRelay.create() |
| 15 | + private var isFlushed = false |
| 16 | + private val outputCache = mutableListOf<Output>() |
| 17 | + |
| 18 | + override val output: Relay<Output> = object : Relay<Output>() { |
| 19 | + |
| 20 | + override fun subscribeActual(observer: Observer<in Output>) { |
| 21 | + exhaust.subscribe(observer) |
| 22 | + } |
| 23 | + |
| 24 | + override fun accept(value: Output) { |
| 25 | + intake.accept(value) |
| 26 | + } |
| 27 | + |
| 28 | + override fun hasObservers() = exhaust.hasObservers() |
| 29 | + |
| 30 | + } |
| 31 | + |
| 32 | + override fun onCreate(lifecycle: Lifecycle) { |
| 33 | + lifecycle.subscribe(onCreate = { flushOutputCache() }) |
| 34 | + } |
| 35 | + |
| 36 | + private val cacheSubscription = intake.subscribe { |
| 37 | + synchronized(this) { |
| 38 | + if (!isFlushed) { |
| 39 | + outputCache.add(it) |
| 40 | + } else { |
| 41 | + exhaust.accept(it) |
| 42 | + switchToExhaust() |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private fun flushOutputCache() { |
| 48 | + synchronized(this) { |
| 49 | + if (isFlushed) error("Already flushed") |
| 50 | + isFlushed = true |
| 51 | + outputCache.forEach { exhaust.accept(it) } |
| 52 | + outputCache.clear() |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + private fun switchToExhaust() { |
| 57 | + intake.subscribe { exhaust.accept(it) } |
| 58 | + cacheSubscription.dispose() |
| 59 | + } |
| 60 | +} |
0 commit comments