Skip to content

Improve SafeBoxStateManager to prevent write operations after SafeBox is CLOSED #19

@harrytmthy

Description

@harrytmthy

Overview

Currently, SafeBoxStateManager emits the CLOSED state when SafeBox.close() is called, signaling that the instance is no longer usable. However, there's no internal guard preventing new write operations (e.g. apply() or commit()) from being launched after this point.

Problem

If external code attempts to launch a write coroutine after SafeBox is closed:

  • The write still proceeds internally (though it may silently fail or emit WRITING after CLOSED).
  • This breaks the expected lifecycle semantics.
  • It may result in confusing logs or race conditions (e.g., .closeWhenIdle() never resolving).

Proposed Solution

Introduce a simple finished flag in SafeBoxStateManager to short-circuit coroutine launches after closure:

private val closed = AtomicBoolean(false)

inline fun launchApplyWithWritingState(...) {
    if (finished.get()) {
        return
    }
    // ...
}

Benefits

  • Prevents illegal state transitions (WRITING after CLOSED)
  • Enforces lifecycle correctness, especially in multithreaded environments
  • Makes SafeBox safer to use in non-singleton, scoped use cases (e.g. ViewModels)

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions