[AI Coding] The Essence of Asynchronous Processing! Mastering Compose with LaunchedEffect and produceState

I used to rely heavily on LaunchedEffect for handling asynchronous operations in Compose,but lately, I’ve realized that produceState might allow for a cleaner and more concise implementation.

So, I asked several AI assistants for their opinions and compared their responses.

 

🤔 GitHub Copilot

  • LaunchedEffect: Suitable for asynchronous operations that modify externally managed states (e.g., ViewModel).
  • produceState: Best for generating and managing asynchronous data directly within Compose.
  • Choose LaunchedEffect for externally managed state, and produceState for internally managed state.


@Composable
fun ExampleScreen(viewModel: MyViewModel = viewModel()) {
    // LaunchedEffect: Update externally managed state asynchronously
    val externalState by viewModel.uiState.collectAsState()
    LaunchedEffect(Unit) {
        viewModel.loadData() // Update external state asynchronously
    }

    // produceState: Generate and manage asynchronous data inside Compose
    val internalState by produceState(initialValue = "Loading...", key1 = viewModel) {
        value = viewModel.loadDataSync() // Assign result to internal state
    }

    Column {
        Text("LaunchedEffect State: $externalState")
        Text("ProduceState State: $internalState")
    }
}

 

🤔 ChatGPT

  • Use LaunchedEffect when updating existing state through side effects.
  • Use produceState when treating the result of an async operation as a state itself.
  • “Generate” with produceState, “manipulate” with LaunchedEffect.



@Composable
fun UserScreen(userId: String) {
    var user by remember { mutableStateOf<User?>(null) }
    LaunchedEffect(userId) { user = api.fetchUser(userId) } // Update existing state

    val userState by produceState<User?>(initialValue = null, key1 = userId) {
        value = api.fetchUser(userId) // Convert async result directly to state
    }

    Text("Launched: ${user?.name ?: "Loading..."}")
    Text("Produced: ${userState?.name ?: "Loading..."}")
}

 

🤔 Gemini

  • produceState: Ideal for exposing results of suspend functions or external data sources as reactive State for the UI.
  • LaunchedEffect: Tied to the composable’s lifecycle, suited for one-time async actions or UI event triggers (e.g., showing a snackbar).
  • State management: produceState handles state automatically, while LaunchedEffect requires manual updates via mutableStateOf.


@Composable
fun UserDataState(userId: String): State<User?> = produceState<User?>(
    initialValue = null,
    key1 = userId // Automatically restarts when key changes
) {
    value = fetchUserFromApi(userId)
}

@Composable
fun EventSnackbar(viewModel: MyViewModel) {
    val scope = rememberCoroutineScope() // Scope for showing snackbar
    LaunchedEffect(Unit) { // Runs once on first composition
        viewModel.uiEvents.collect { event ->
            // Receive UI event and trigger a side effect (e.g., show snackbar)
            scope.launch { SnackbarHostState.showSnackbar("Received event!") }
        }
    }
}

 

🤔 Summary

  • LaunchedEffect: Used when updating externally managed states (e.g., ViewModel) through asynchronous operations.
  • produceState: Used when generating and managing the result of asynchronous processing directly as state within Compose.
  • If the state is managed externally, use LaunchedEffect; if it’s internally generated, use produceState.
  • LaunchedEffect requires manual state updates, while produceState automatically manages state.
  • Use LaunchedEffect to update external state, and produceState to generate internal state.
  • LaunchedEffect manipulates existing state through side effects.
  • produceState creates new state from asynchronous results.
  • Operate state = LaunchedEffect / Generate state = produceState
  • produceState: Ideal for exposing asynchronous results as automatically managed State objects for the UI.
  • LaunchedEffect: Used to manually update existing states (e.g., ViewModel’s state) or trigger side effects such as showing a snackbar.
  • Where the state is managed: If it’s generated within Compose → use produceState.
  • Where the state is managed: If it’s controlled outside Compose (e.g., ViewModel) → use LaunchedEffect.

👉 【AIコーディング】非同期処理の極意!LaunchEffect と produceState の使い分けで Jetpack Compose を制す


初回コンポーズは Activity.onStart() までに終わる

 

🤔 Activity x Compose のライフサイクル


Activity.onCreate()
  setContent { ... }   ← ComposeView をセット

    ↓

  [初回コンポーズ(First Composition)]
    ・Composable を評価し UI を構築
    ・LaunchedEffect → コミット後に一度実行
    ・SideEffect → 各コミットごとに実行
    ・DisposableEffect → onDispose 定義

    ↓

Activity.onStart()

    ↓

Activity.onResume()

    ↓

  [再コンポーズ(Recomposition)]  
    ・状態変更に応じて必要部分のみ再評価
    ・LaunchedEffect は再実行されない(Key 変更時のみ)
    ・SideEffect / DisposableEffect は再評価

    ↓

Activity.onPause()

    ↓

  (ComposeView は保持)
    ・UI は部分的に見えなくなる
    ・状態は Composition 内で維持

    ↓

Activity.onStop() 

    ↓

  [破棄準備(Dispose 検知)]
    ・ViewCompositionStrategy による破棄条件監視

    ↓

Activity.onDestroy()

    ↓

  [破棄(Dispose)]
    ・ComposeView が破棄される
    ・DisposableEffect.onDispose() 実行

 

🤔 まとめ

初回コンポーズは Activity.onStart() までに終わる。

👉 これだけでわかる!Activity × Compose のライフサイクル完全図解 🚀


IDE × AIモデル別:プロンプトに食わせるべきファイルまとめ

主要IDEごとに、連携AI・推奨ファイル・目的・補足を整理した表です。プログラミング中心にまとめています。

1. 基本のセット

  • プロジェクト概要・設計
    README.md, architecture.md
    AIに全体像・設計方針・責務を理解させる
  • 依存・環境情報
    build.gradle(.kts), package.json, Podfile, .env.example
    SDK・ライブラリ・環境変数を正確に認識させる
  • コーディング方針・ルール
    .prompt.yaml, .copilot-instructions.md, .editorconfig
    命名規則、禁止API、コードスタイルを統一

2. IDE × AIモデル別の推奨ファイルと効果

IDE 推奨AIモデル 重点ファイル 効果 補足
Android Studio / IntelliJ Gemini Code Assist, Copilot .prompt.yaml, build.gradle, architecture.md Androidプロジェクト全体を理解した補完・設計提案 プロジェクト全体の構造を解析可能。方針ファイルで安定化。
Xcode Copilot, GPT-5 .prompt.yaml, Package.swift, README.md SwiftUI/MVVM設計に沿った正確なコード生成 Xcodeは依存解析が弱めなので .prompt.yaml を明示すると効果大。
VS Code Copilot Chat, GPT-5 .copilot-instructions.md, package.json, README.md 軽量環境で多言語対応、チーム開発の方針共有に有効 拡張機能単位でAI切替可能。指示ファイルが最重要。
Cursor / Windsurf / Aider GPT-5 / Claude 3.5 / Gemini 1.5 .prompt.yaml / .cursorconfig, README.md, architecture.md, build設定 設計・生成・リファクタを自動で分担 ファイル単位でAIが文脈キャッシュを保持。設計書参照可。
Jupyter / DataSpell / VSCode + Python GPT-4 Turbo, Gemini Advanced .ipynb / .csv / .xlsx, analysis.md / README.md, .prompt.yaml データ解析・統計・グラフ生成 データ+分析目的+出力形式を渡すと的確に解析可能。
Figma / Webflow / Framer Gemini 1.5 Pro (Vision), GPT-5 Vision .fig / .svg / layout.json, style_reference.jpg, .prompt.yaml UIデザイン→コード変換・スタイル抽出 構図+目的+出力フォーマット指定でSwiftUIやComposeコード化が容易。

3. 実務での運用Tips

  • サンプルコードを渡す
    /sample_code に小さな動作例を置くと、AIが文体やパターンを模倣しやすい
  • 変更履歴を渡す
    CHANGELOG.md や feature_list.md を読むことで、過去の修正意図を理解し、安全な提案が可能
  • 大きなファイルは要約して渡す
    設計書や長文ドキュメントは、AIの文脈理解の負荷を減らすために必要部分だけ渡す
  • 依存関係やAPI仕様は明示
    未定義関数や古いAPIの誤提案を防ぐため、build.gradle や .env.example を食わせる

4. まとめ

プログラミングAIを「単なるコード補完」ではなく、プロジェクト理解型のアシスタントとして活用するには、

「概要 + 環境 + 方針」をAIに与えることが最も重要です。

  • IDEや言語に合わせたファイルを食わせる
  • 設計方針と依存関係を明確化する
  • サンプルコードや履歴で文脈を補完する

この3ステップで、AIは理解に基づいたコード生成・設計提案を行い、開発効率と品質を大幅に向上させられます。