|
| 1 | +/* |
| 2 | + * Designed and developed by 2024 skydoves (Jaewoong Eum) |
| 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 | +@file:OptIn(ExperimentalCoroutinesApi::class) |
| 17 | + |
| 18 | +package com.skydoves.pokedex.compose.feature.details |
| 19 | + |
| 20 | +import android.util.Log |
| 21 | +import kotlinx.coroutines.CoroutineScope |
| 22 | +import kotlinx.coroutines.ExperimentalCoroutinesApi |
| 23 | +import kotlinx.coroutines.delay |
| 24 | +import kotlinx.coroutines.flow.Flow |
| 25 | +import kotlinx.coroutines.flow.MutableStateFlow |
| 26 | +import kotlinx.coroutines.flow.SharingCommand |
| 27 | +import kotlinx.coroutines.flow.SharingStarted |
| 28 | +import kotlinx.coroutines.flow.StateFlow |
| 29 | +import kotlinx.coroutines.flow.combine |
| 30 | +import kotlinx.coroutines.flow.distinctUntilChanged |
| 31 | +import kotlinx.coroutines.flow.dropWhile |
| 32 | +import kotlinx.coroutines.flow.stateIn |
| 33 | +import kotlinx.coroutines.flow.transformLatest |
| 34 | + |
| 35 | +/** |
| 36 | + * Create an upstream cold flow as a StateFlow that triggers the upstream operation only once, |
| 37 | + * preventing re-execution no matter how many times it's subscribed. |
| 38 | + * After the initial emission, it will simply replay the latest cached value. |
| 39 | + * |
| 40 | + * @param scope the coroutine scope in which sharing is started. |
| 41 | + * @param stopTimeout configures a delay (in milliseconds) between the disappearance of the last |
| 42 | + * subscriber and the stopping of the sharing coroutine. It defaults to zero (stop immediately). |
| 43 | + * @param replayExpiration configures a delay (in milliseconds) between the stopping of |
| 44 | + * the sharing coroutine and the resetting of the replay cache (which makes the cache empty for the |
| 45 | + * [shareIn] operator and resets the cached value to the original `initialValue` |
| 46 | + * for the [stateIn] operator). It defaults to `Long.MAX_VALUE` (keep replay cache forever, |
| 47 | + * never reset buffer). Use zero value to expire the cache immediately. |
| 48 | + * @param initialValue the initial value of the state flow. This value is also used when the |
| 49 | + * state flow is reset using the [SharingStarted]. [WhileSubscribed] strategy with the |
| 50 | + * [replayExpiration] parameter. |
| 51 | + */ |
| 52 | +public fun <T> Flow<T>.onetimeStateIn( |
| 53 | + scope: CoroutineScope, |
| 54 | + stopTimeout: Long = 0, |
| 55 | + replayExpiration: Long = Long.MAX_VALUE, |
| 56 | + initialValue: T, |
| 57 | +): StateFlow<T> { |
| 58 | + return stateIn( |
| 59 | + scope = scope, |
| 60 | + started = OnetimeWhileSubscribed( |
| 61 | + stopTimeout = stopTimeout, |
| 62 | + replayExpiration = replayExpiration, |
| 63 | + ), |
| 64 | + initialValue, |
| 65 | + ) |
| 66 | +} |
| 67 | + |
| 68 | +/** |
| 69 | + * This is a companion extension of [SharingStarted], which is a [SharingStarted] strategy |
| 70 | + * designed to limit upstream emissions to only once. After the initial emission, |
| 71 | + * it remains inactive until an active subscriber reappears. |
| 72 | + * |
| 73 | + * @param stopTimeout configures a delay (in milliseconds) between the disappearance of the last |
| 74 | + * subscriber and the stopping of the sharing coroutine. It defaults to zero (stop immediately). |
| 75 | + * @param replayExpiration configures a delay (in milliseconds) between the stopping of |
| 76 | + * the sharing coroutine and the resetting of the replay cache (which makes the cache empty for the |
| 77 | + * [shareIn] operator and resets the cached value to the original `initialValue` |
| 78 | + * for the [stateIn] operator). It defaults to `Long.MAX_VALUE` (keep replay cache forever, |
| 79 | + * never reset buffer). Use zero value to expire the cache immediately. |
| 80 | + */ |
| 81 | +public fun SharingStarted.Companion.OnetimeWhileSubscribed( |
| 82 | + stopTimeout: Long, |
| 83 | + replayExpiration: Long = Long.MAX_VALUE, |
| 84 | +): OnetimeWhileSubscribed { |
| 85 | + return OnetimeWhileSubscribed( |
| 86 | + stopTimeout = stopTimeout, |
| 87 | + replayExpiration = replayExpiration, |
| 88 | + ) |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * `OnetimeWhileSubscribed` is a [SharingStarted] strategy designed to limit upstream emissions to |
| 93 | + * only once. After the initial emission, it remains inactive until an active subscriber reappears. |
| 94 | + * |
| 95 | + * @param stopTimeout configures a delay (in milliseconds) between the disappearance of the last |
| 96 | + * subscriber and the stopping of the sharing coroutine. It defaults to zero (stop immediately). |
| 97 | + * @param replayExpiration configures a delay (in milliseconds) between the stopping of |
| 98 | + * the sharing coroutine and the resetting of the replay cache (which makes the cache empty for the |
| 99 | + * [shareIn] operator and resets the cached value to the original `initialValue` |
| 100 | + * for the [stateIn] operator). It defaults to `Long.MAX_VALUE` (keep replay cache forever, |
| 101 | + * never reset buffer). Use zero value to expire the cache immediately. |
| 102 | + */ |
| 103 | +public class OnetimeWhileSubscribed( |
| 104 | + private val stopTimeout: Long, |
| 105 | + private val replayExpiration: Long, |
| 106 | +) : SharingStarted { |
| 107 | + |
| 108 | + private val hasCollected: MutableStateFlow<Boolean> = MutableStateFlow(false) |
| 109 | + |
| 110 | + init { |
| 111 | + require(stopTimeout >= 0) { "stopTimeout($stopTimeout ms) cannot be negative" } |
| 112 | + require(replayExpiration >= 0) { "replayExpiration($replayExpiration ms) cannot be negative" } |
| 113 | + } |
| 114 | + |
| 115 | + override fun command(subscriptionCount: StateFlow<Int>): Flow<SharingCommand> = |
| 116 | + combine(hasCollected, subscriptionCount) { collected, counts -> |
| 117 | + collected to counts |
| 118 | + } |
| 119 | + .transformLatest { pair -> |
| 120 | + val (collected, count) = pair |
| 121 | + if (count > 0 && !collected) { |
| 122 | + emit(SharingCommand.START) |
| 123 | + hasCollected.value = true |
| 124 | + } else { |
| 125 | + delay(stopTimeout) |
| 126 | + if (replayExpiration > 0) { |
| 127 | + emit(SharingCommand.STOP) |
| 128 | + delay(replayExpiration) |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + .dropWhile { |
| 133 | + it != SharingCommand.START |
| 134 | + } // don't emit any STOP/RESET_BUFFER to start with, only START |
| 135 | + .distinctUntilChanged() // just in case somebody forgets it, don't leak our multiple sending of START |
| 136 | + |
| 137 | + override fun toString(): String { |
| 138 | + val params = buildList(2) { |
| 139 | + if (stopTimeout > 0) add("stopTimeout=${stopTimeout}ms") |
| 140 | + if (replayExpiration < Long.MAX_VALUE) add("replayExpiration=${replayExpiration}ms") |
| 141 | + } |
| 142 | + return "SharingStarted.WhileSubscribed(${params.joinToString()})" |
| 143 | + } |
| 144 | + |
| 145 | + // equals & hashcode to facilitate testing, not documented in public contract |
| 146 | + override fun equals(other: Any?): Boolean = |
| 147 | + other is OnetimeWhileSubscribed && |
| 148 | + stopTimeout == other.stopTimeout && |
| 149 | + replayExpiration == other.replayExpiration |
| 150 | + |
| 151 | + override fun hashCode(): Int = stopTimeout.hashCode() * 31 + replayExpiration.hashCode() |
| 152 | +} |
0 commit comments