kotlin

Flow - SharedFlow, MutableSharedFlow

whjungdev 2024. 10. 15. 15:00

SharedFlow

  • Immutable: SharedFlow는 읽기 전용입니다. 외부에서 값을 직접 수정할 수 없습니다.
  • 구독 가능: 여러 구독자가 있을 수 있으며, 구독자는 방출된 값을 받을 수 있습니다.
  • Replay: 이전 값을 저장하고 새 구독자가 구독할 때 그 값을 받을 수 있도록 설정할 수 있습니다.
  • 백프레셔: 수신자가 처리할 수 없는 경우에 대한 대처 메커니즘이 내장되어 있습니다.
public interface SharedFlow<out T> : Flow<T> {
    /**
     * A snapshot of the replay cache.
     */
    public val replayCache: List<T>

    /**
     * Accepts the given [collector] and [emits][FlowCollector.emit] values into it.
     * To emit values from a shared flow into a specific collector, either `collector.emitAll(flow)` or `collect { ... }`
     * SAM-conversion can be used.
     *
     * **A shared flow never completes**. A call to [Flow.collect] or any other terminal operator
     * on a shared flow never completes normally.
     *
     * @see [Flow.collect] for implementation and inheritance details.
     */
    override suspend fun collect(collector: FlowCollector<T>): Nothing
}

 

MutableSharedFlow

  • Mutable: MutableSharedFlow는 값을 방출할 수 있는 mutable(변경 가능한) 버전입니다. 이를 통해 외부에서 값 방출을 할 수 있습니다.
  • emit() 메서드: 새로운 값을 방출할 수 있는 emit() 메서드를 제공합니다.
  • SharedFlow의 서브클래스: MutableSharedFlow는 SharedFlow의 서브클래스이며, 결국 SharedFlow로 취급될 수 있습니다.
@Suppress("FunctionName", "UNCHECKED_CAST")
public fun <T> MutableSharedFlow(
    replay: Int = 0,
    extraBufferCapacity: Int = 0,
    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND
): MutableSharedFlow<T> {
    require(replay >= 0) { "replay cannot be negative, but was $replay" }
    require(extraBufferCapacity >= 0) { "extraBufferCapacity cannot be negative, but was $extraBufferCapacity" }
    require(replay > 0 || extraBufferCapacity > 0 || onBufferOverflow == BufferOverflow.SUSPEND) {
        "replay or extraBufferCapacity must be positive with non-default onBufferOverflow strategy $onBufferOverflow"
    }
    val bufferCapacity0 = replay + extraBufferCapacity
    val bufferCapacity = if (bufferCapacity0 < 0) Int.MAX_VALUE else bufferCapacity0 // coerce to MAX_VALUE on overflow
    return SharedFlowImpl(replay, bufferCapacity, onBufferOverflow)
}

'kotlin' 카테고리의 다른 글

StateFlow vs SharedFlow  (0) 2024.10.15
StateFlow  (0) 2024.10.15