Generate state management for asynchronous data loading as a sealed interface-based state machine. Clearly distinguish initial loading (initialLoad) from refresh (refresh), and use it in combination with Compose UI helpers.
Usage
Confirmation items
Confirm the following before code generation. Items that can be clearly read from the user's instructions may be omitted from confirmation.
- Target module — The module in which to place SimpleLoader (e.g.,
ui/core,shared) - Package name — Estimate from the existing structure and propose
- Generated files — Select from the following (default: all)
-
SimpleLoader.kt+SimpleLoaderFactory.kt— Core (required) -
SimpleLoaderExt.kt— Extension functions (dataOrNull,exceptionOrNull) -
SimpleLoaderLogger.kt— Logging -
IllegalStateTransitionHandler.kt— Invalid transition handler -
SimpleLoaderWithPartialData.kt— Partial data support - UI helpers (
View.kt,AnimatedView.kt,InitialLoadingView.kt,InitialErrorView.kt)
-
Skip conditions
In the following cases, skip confirmation and generate with default settings:
- "By default" / "Generate everything" / "with default settings"
Generation procedure
Step 1: Project analysis
build.gradle.ktsCheck and determine KMP / Android / JVM- Identify source directory patterns:
- KMP:
<module>/src/commonMain/kotlin/ - Android/JVM:
<module>/src/main/kotlin/
- KMP:
- Search for any existing Loader-related classes
Step 2: Generate core files
example/ Copy the files in and replace the package name with sed .
cp <EXAMPLE_DIR>/simple/*.kt <TARGET_DIR>/simple/
cp <EXAMPLE_DIR>/IllegalStateTransitionHandler.kt <TARGET_DIR>/
sed -i '' 's/package me\.tbsten\.simpleloader/package <USER_PACKAGE>/g' <TARGET_DIR>/**/*.kt
sed -i '' 's/import me\.tbsten\.simpleloader\./import <USER_PACKAGE>./g' <TARGET_DIR>/**/*.kt
Generated file structure:
<target>/loader/
├── IllegalStateTransitionHandler.kt
└── simple/
├── SimpleLoader.kt # interface + State sealed interface + Impl + Fake
├── SimpleLoaderFactory.kt # Factory interface
├── SimpleLoaderExt.kt # dataOrNull, dataOr, exceptionOrNull
├── SimpleLoaderLogger.kt # fun interface Logger
├── SimpleLoaderWithPartialData.kt # PartialData support
└── ui/
├── View.kt # State<Data>.View() composable
├── AnimatedView.kt # State<Data>.AnimatedView() with transitions
├── InitialLoadingView.kt # Default loading indicator
└── InitialErrorView.kt # Default error with retry button
Step 3: Check dependencies
build.gradle.kts Check whether the following are included in and propose additions if any are missing:
kotlinx-coroutines-core— Requiredkotlinx-serialization— State の@SerializableRequired for (optional)androidx.compose— Required for UI helpersandroidx.lifecycle— Required for ViewModel integration
Step 4: Build verification
# KMP
./gradlew :<module>:compileKotlinJvm
# Android
./gradlew :<module>:compileDebugKotlin
Step 5: Completion message
## 生成完了
**パッケージ**: `<package>`
**出力先**: `<output_dir>`
### 生成ファイル
- SimpleLoader.kt + SimpleLoaderFactory.kt
- ...
### 依存関係
- [変更なし / 追加: ...]
### ビルド結果
- [SUCCESS / FAILED]
Usage patterns
The actual usage of SimpleLoader is shown below. Detailed sample code is available in references/.
Pattern 1: Define a Loader with typealias + Factory
// 1. ドメイン固有の Loader 型を typealias で定義
typealias ItemListLoader = SimpleLoader<List<Item>>
// 2. Factory で実装を生成し、DI でバインド
class ItemListLoaderImpl(
getItemListUseCase: GetItemListUseCase,
simpleLoaderFactory: SimpleLoaderFactory,
) : ItemListLoader by simpleLoaderFactory.create(
coroutineScope = MainScope(),
load = { getItemListUseCase() },
)
Pattern 2: Usage in a ViewModel
class HomeViewModel(
private val itemListLoader: ItemListLoader,
) : ViewModel(itemListLoader) { // AutoCloseable として渡す
// StateFlow をデリゲートで公開
val loadItemListState by itemListLoader::state
init {
itemListLoader.initialLoad() // 初回読み込み
}
fun refresh() = itemListLoader.refresh() // リフレッシュ
}
Pattern 3: State display in Compose UI
@Composable
fun HomeScreen(viewModel: HomeViewModel) {
val state by viewModel.loadItemListState.collectAsStateWithLifecycle()
state.AnimatedView(
onInitialErrorRefresh = viewModel::refresh,
initialLoading = { SkeletonView() }, // カスタムローディング
) { state ->
// ViewWithDataScope 内: isRefreshLoading, isRefreshError が使える
ItemListView(
itemList = state.data,
isRefreshLoading = isRefreshLoading,
)
}
}
Pattern 4: Usage in tests
// FakeSimpleLoader でテスト
val fakeLoader = FakeSimpleLoader<List<String>>(
coroutineScope = TestScope(),
state = SimpleLoader.State.Loaded(listOf("item1", "item2")),
)
val viewModel = HomeViewModel(itemListLoader = fakeLoader)
State transition diagram
Initial ──initialLoad()──► InitialLoading ──success──► Loaded
│ │
└──failure──► InitialError │
│
Loaded ──refresh()──► RefreshLoading ──success──► Loaded
│
└──failure──► RefreshError
load()automatically selects according to the current stateinitialLoad()かrefresh()automatically select- during Loading
load()calls are notified byIllegalStateTransitionReasonwith IllegalStateTransitionReason