RRTutors
Android & AI Module 1: Topic 4

Production Routing, Streams & Agent State Management

By RR Tutors Editorial Updated July 2026

To ship code-first AI features to real users, you need a way to manage persistent memory sessions and handle network latency gracefully. This tutorial implements the AgentRunner execution loop using Kotlin coroutines and native reactive architecture.

Managing Memory and State Loops

Google ADK decouples agent processing entirely from short-lived views. Execution runs inside an **AgentRunner session context**. This session tracks the exact chat context historical state arrays and safely emits chunks via standard asynchronous reactive streams.

Implementation: Stream Processing in a ViewModel Layer

Below is a clean architecture implementation of an Android ViewModel capturing text outputs dynamically from an ADK runner loop:

package com.example.adkdemoapp.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.adkdemoapp.agents.PrimaryRouterAgent
import com.google.adk.kt.runners.AgentRunner
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class AgentDashboardViewModel : ViewModel() {

    private val _uiState = MutableStateFlow("")
    val uiState: StateFlow = _uiState

    // Initializing the long-lived, state-managed session runner
    private val runner = AgentRunner.create(agent = PrimaryRouterAgent.orchestrator)

    fun sendUserMessage(prompt: String) {
        viewModelScope.launch {
            _uiState.value = "Thinking..."
            
            // Execute runtime orchestration loop tracking session context history
            runner.executeStream(prompt).collect { chunk ->
                if (_uiState.value == "Thinking...") {
                    _uiState.value = ""
                }
                // Append asynchronous reactive text stream parts instantly to UI
                _uiState.value += chunk.textDelta
            }
        }
    }
}

Module 1 Wrap-up Summary

Congratulations! You have completed **Module 1: Core Framework Setup & Architecture**. You have successfully built a code-first root agent infrastructure, wired decoupled multi-agent swarm layers, leveraged KSP processing for type-safe functional tooling, and bounded everything safely behind production-grade ViewModel reactive data flows.