💨

Compose MultiplatformプロジェクトでのFirebase統合アーキテクチャ

に公開

はじめに

私はCheerDailyという、日々の振り返りとタスク管理をサポートするCompose Multiplatformアプリを開発しました。ユーザーが日記を書くとAIメンターが評価・励ましのフィードバックを提供し、モチベーション維持を支援するアプリです。

CheerDailyの開発において、Firebase(Authentication、Firestore、Remote Config、Firebase AI)をAndroid/iOS両プラットフォームで統合する必要がありました。既存のKMP向けFirebaseライブラリもありましたが、最新機能への対応速度や柔軟性の観点から、ネイティブSDKを直接使うexpect/actualパターン + Swift実装によるアーキテクチャを採用しました。

本記事では、CheerDailyで採用したこのFirebase統合アーキテクチャを解説します。ただし、セキュリティ上の理由から実際のコードをそのまま掲載することは避け、**同様のアーキテクチャを持つ架空のメモアプリ「NoteKeeper」**を例に技術的な実装を説明します。

CheerDailyにおけるFirebaseの役割

参考までに、CheerDailyでFirebaseが担っている役割を紹介します:

Firebase サービス CheerDailyでの役割
Firebase Authentication Google/Apple Sign-Inによるユーザー認証
Cloud Firestore 日記データとタスクの同期・バックアップ
Firebase Remote Config AIメンターのプロンプトを動的配信
Firebase AI (Gemini API) 日記に対するAI評価・フィードバック生成

技術解説で使用する架空アプリ「NoteKeeper」について

NoteKeeperは、CheerDailyと同じFirebaseサービスを使用するシンプルなメモ管理アプリという設定で、以下の機能を持ちます:

  • メモ作成・編集
  • カテゴリ分類
  • AI自動要約機能
  • データ同期・バックアップ

本記事で紹介するアーキテクチャパターンとFirebase統合方法は、CheerDailyとNoteKeeperで共通しています。

なぜ既存のKMP Firebaseライブラリを使わなかったのか

現在、KMP向けFirebaseライブラリ(例: dev.gitlive:firebase-kotlin-sdk)は存在しますが、以下の理由から採用しませんでした:

  1. 最新Firebase機能への対応速度: Firebase AI (Gemini API) などの最新機能はネイティブSDKで先行リリースされるため、ラッパーライブラリでは対応が遅れる
  2. プラットフォーム固有の最適化: Android/iOSそれぞれのネイティブSDKを直接使うことで、各プラットフォーム特有の最適化やベストプラクティスを活用可能
  3. 柔軟性とコントロール: ラッパーライブラリに依存せず、必要な機能を自由に実装・カスタマイズできる
  4. 型安全性とSwift連携: iOSではSwiftでFirebase SDKを直接使い、Kotlinインターフェースに準拠させることで、両プラットフォームの型システムを最大限活用

アーキテクチャ概要

本プロジェクトでは expect/actual パターン を活用し、以下の構成でFirebaseを統合しています:

commonMain/
  └─ interface定義 (expect宣言)

androidMain/
  └─ Kotlin actual実装
     └─ Firebase Android SDK使用

iosMain/
  └─ Kotlin expect宣言のみ

iosApp/ (Swift)
  └─ Swift実装
     └─ Firebase iOS SDK使用
     └─ Kotlinインターフェースに準拠

ポイント: iOSではSwiftでFirebase SDKを使い、Kotlinから公開されたインターフェースに準拠するクラスを実装。これをKoin DIに注入することで、Kotlin側から透過的に利用可能にしています。

実装例

1. Firebase Authentication

commonMain - インターフェース定義

// composeApp/src/commonMain/kotlin/com/example/notekeeper/data/auth/AuthClient.kt
interface AuthClient {
    val currentUserId: String?
    val currentUserEmail: String?
    suspend fun signInWithGoogle(): String
    suspend fun signInWithApple(): String
    suspend fun signOut()
    suspend fun deleteAccount()
    fun addAuthStateListener(listener: (String?) -> Unit)
    fun removeAuthStateListener(listener: (String?) -> Unit)
}

androidMain - Kotlin actual実装

// composeApp/src/androidMain/kotlin/com/example/notekeeper/data/auth/AuthClient.android.kt
class AuthClientImpl(
    private val context: Context
) : AuthClient {
    
    private val auth: FirebaseAuth by lazy { Firebase.auth }
    
    override val currentUserId: String?
        get() = auth.currentUser?.uid
    
    override suspend fun signInWithGoogle(): String = withContext(Dispatchers.IO) {
        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(context.getString(R.string.web_client_id))
            .requestEmail()
            .build()
        
        val googleSignInClient = GoogleSignIn.getClient(context, gso)
        val signInIntent = googleSignInClient.signInIntent
        
        // ActivityResultを使ってGoogle Sign-Inフローを実行
        // 成功時にFirebaseAuthにサインイン
        // ...実装詳細省略...
        
        auth.currentUser?.uid ?: throw Exception("Sign-in failed")
    }
}

iOS - Swift実装

// iosApp/iosApp/AuthClientImpl.swift
import FirebaseAuth
import ComposeApp

public class AuthClientImpl: NSObject {
    private var authStateListeners: [String: (String?) -> Void] = [:]
    
    public override init() {
        super.init()
    }
}

extension AuthClientImpl: AuthClient {
    public var currentUserId: String? {
        return Auth.auth().currentUser?.uid
    }
    
    public func signInWithGoogle() async throws -> String {
        // Google Sign-In SDK for iOSを使用
        // Firebase Authに認証情報を渡してサインイン
        // ...実装詳細省略...
        
        guard let userId = Auth.auth().currentUser?.uid else {
            throw NSError(domain: "AuthError", code: -1)
        }
        return userId
    }
    
    public func signInWithApple() async throws -> String {
        // Apple Sign-In実装
        // AuthenticationServices frameworkを使用
        // ...実装詳細省略...
        
        guard let userId = Auth.auth().currentUser?.uid else {
            throw NSError(domain: "AuthError", code: -1)
        }
        return userId
    }
}

2. Cloud Firestore

commonMain - インターフェース定義

// composeApp/src/commonMain/kotlin/com/example/notekeeper/data/sync/SyncService.kt
interface SyncService {
    suspend fun uploadNote(userId: String, note: Note)
    suspend fun uploadCategory(userId: String, category: Category)
    suspend fun downloadAllNotes(userId: String): List<Note>
    suspend fun downloadAllCategories(userId: String): List<Category>
    suspend fun recordSummary(userId: String, summary: AISummaryHistory)
    suspend fun getSummaryCount(userId: String, noteId: String): Int
}

androidMain - Kotlin actual実装

// composeApp/src/androidMain/kotlin/com/example/notekeeper/data/sync/SyncService.android.kt
class SyncServiceImpl : SyncService {
    
    private val firestore: FirebaseFirestore by lazy {
        FirebaseFirestore.getInstance()
    }
    
    override suspend fun uploadNote(userId: String, note: Note) {
        val noteData = mapOf(
            "id" to note.id,
            "title" to note.title,
            "content" to note.content,
            "categoryId" to note.categoryId,
            "createdAt" to note.createdAt,
            "updatedAt" to note.updatedAt
        )
        
        firestore.collection("users")
            .document(userId)
            .collection("notes")
            .document(note.id)
            .set(noteData)
            .await()
    }
    
    override suspend fun downloadAllNotes(userId: String): List<Note> {
        val snapshot = firestore.collection("users")
            .document(userId)
            .collection("notes")
            .get()
            .await()
            
        return snapshot.documents.mapNotNull { doc ->
            Note(
                id = doc.getString("id") ?: return@mapNotNull null,
                title = doc.getString("title") ?: "",
                content = doc.getString("content") ?: "",
                categoryId = doc.getString("categoryId"),
                createdAt = doc.getString("createdAt") ?: "",
                updatedAt = doc.getString("updatedAt") ?: ""
            )
        }
    }
}

iOS - Swift実装

// iosApp/iosApp/SyncServiceImpl.swift
import FirebaseFirestore
import ComposeApp

public class SyncServiceImpl: NSObject {
    private let firestore: Firestore
    
    public override init() {
        self.firestore = Firestore.firestore()
        super.init()
    }
}

extension SyncServiceImpl: SyncService {
    
    public func uploadNote(userId: String, note: Note) async throws {
        let noteData: [String: Any] = [
            "id": note.id,
            "title": note.title,
            "content": note.content,
            "categoryId": note.categoryId ?? NSNull(),
            "createdAt": note.createdAt,
            "updatedAt": note.updatedAt
        ]
        
        try await firestore
            .collection("users")
            .document(userId)
            .collection("notes")
            .document(note.id)
            .setData(noteData)
    }
    
    public func downloadAllNotes(userId: String) async throws -> [Note] {
        let snapshot = try await firestore
            .collection("users")
            .document(userId)
            .collection("notes")
            .getDocuments()
            
        return snapshot.documents.compactMap { document in
            let data = document.data()
            
            guard let id = data["id"] as? String,
                  let title = data["title"] as? String,
                  let content = data["content"] as? String,
                  let createdAt = data["createdAt"] as? String,
                  let updatedAt = data["updatedAt"] as? String
            else {
                return nil
            }
            
            return Note(
                id: id,
                title: title,
                content: content,
                categoryId: data["categoryId"] as? String,
                createdAt: createdAt,
                updatedAt: updatedAt
            )
        }
    }
}

3. Firebase Remote Config

commonMain - インターフェース定義

// composeApp/src/commonMain/kotlin/com/example/notekeeper/data/config/ConfigClient.kt
interface ConfigClient {
    suspend fun fetchAndActivate(): Boolean
    suspend fun getString(key: String): String
    suspend fun getSummaryPrompt(summaryType: SummaryType): String
}

object ConfigKeys {
    const val SUMMARY_PROMPT_BRIEF = "summary_prompt_brief"
    const val SUMMARY_PROMPT_DETAILED = "summary_prompt_detailed"
    const val SUMMARY_PROMPT_BULLET = "summary_prompt_bullet"
}

object DefaultPrompts {
    const val BRIEF = """あなたは簡潔な要約を作成するアシスタントです。
以下のメモ内容を読んで、3文以内で要点をまとめてください。"""

    const val DETAILED = """あなたは詳細な要約を作成するアシスタントです。
以下のメモ内容を読んで、詳細な要約を作成してください。"""

    const val BULLET = """あなたは箇条書きで要約を作成するアシスタントです。
以下のメモ内容を読んで、箇条書きで要点をまとめてください。"""
}

androidMain - Kotlin actual実装

// composeApp/src/androidMain/kotlin/com/example/notekeeper/data/config/ConfigClient.android.kt
class ConfigClientImpl : ConfigClient {
    
    private val remoteConfig: FirebaseRemoteConfig by lazy {
        Firebase.remoteConfig.apply {
            setConfigSettingsAsync(
                remoteConfigSettings {
                    minimumFetchIntervalInSeconds = 3600
                }
            )
            setDefaultsAsync(
                mapOf(
                    ConfigKeys.SUMMARY_PROMPT_BRIEF to DefaultPrompts.BRIEF,
                    ConfigKeys.SUMMARY_PROMPT_DETAILED to DefaultPrompts.DETAILED,
                    ConfigKeys.SUMMARY_PROMPT_BULLET to DefaultPrompts.BULLET
                )
            )
        }
    }
    
    override suspend fun getSummaryPrompt(summaryType: SummaryType): String {
        val key = when (summaryType) {
            SummaryType.BRIEF -> ConfigKeys.SUMMARY_PROMPT_BRIEF
            SummaryType.DETAILED -> ConfigKeys.SUMMARY_PROMPT_DETAILED
            SummaryType.BULLET -> ConfigKeys.SUMMARY_PROMPT_BULLET
        }
        return remoteConfig.getString(key)
    }
}

iOS - Swift実装

// iosApp/iosApp/ConfigClientImpl.swift
import FirebaseRemoteConfig
import ComposeApp

public class ConfigClientImpl: NSObject {
    private let remoteConfig: RemoteConfig
    
    public override init() {
        self.remoteConfig = RemoteConfig.remoteConfig()
        
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 3600
        self.remoteConfig.configSettings = settings
        
        self.remoteConfig.setDefaults([
            ConfigKeys.shared.SUMMARY_PROMPT_BRIEF: DefaultPrompts.shared.BRIEF as NSString,
            ConfigKeys.shared.SUMMARY_PROMPT_DETAILED: DefaultPrompts.shared.DETAILED as NSString,
            ConfigKeys.shared.SUMMARY_PROMPT_BULLET: DefaultPrompts.shared.BULLET as NSString
        ])
        
        super.init()
    }
}

extension ConfigClientImpl: ConfigClient {
    
    public func getSummaryPrompt(summaryType: SummaryType) async throws -> String {
        var key: String
        var defaultPrompt: String
        
        switch summaryType {
        case .brief:
            key = ConfigKeys.shared.SUMMARY_PROMPT_BRIEF
            defaultPrompt = DefaultPrompts.shared.BRIEF
        case .detailed:
            key = ConfigKeys.shared.SUMMARY_PROMPT_DETAILED
            defaultPrompt = DefaultPrompts.shared.DETAILED
        case .bullet:
            key = ConfigKeys.shared.SUMMARY_PROMPT_BULLET
            defaultPrompt = DefaultPrompts.shared.BULLET
        @unknown default:
            return ""
        }
        
        let value = self.remoteConfig.configValue(forKey: key).stringValue ?? defaultPrompt
        return value
    }
}

4. Firebase AI (Gemini API)

commonMain - インターフェース定義

// composeApp/src/commonMain/kotlin/com/example/notekeeper/data/ai/AIClient.kt
interface AIClient {
    suspend fun summarizeNote(
        noteContent: String,
        summaryType: SummaryType,
        configClient: ConfigClient
    ): String
}

androidMain - Kotlin actual実装

// composeApp/src/androidMain/kotlin/com/example/notekeeper/data/ai/AIClient.android.kt
class AIClientImpl : AIClient {
    
    private val generativeModel by lazy {
        Firebase.ai(backend = GenerativeBackend.googleAI())
            .generativeModel("gemini-2.0-flash-lite")
    }
    
    override suspend fun summarizeNote(
        noteContent: String,
        summaryType: SummaryType,
        configClient: ConfigClient
    ): String = withContext(Dispatchers.IO) {
        withTimeout(30_000L) {
            val systemPrompt = configClient.getSummaryPrompt(summaryType)
            val fullPrompt = """
                $systemPrompt
                
                【メモ内容】
                $noteContent
            """.trimIndent()
            
            val response = generativeModel.generateContent(fullPrompt)
            response.text?.trim() ?: "要約の生成に失敗しました。"
        }
    }
}

iOS - Swift実装

// iosApp/iosApp/AIClientImpl.swift
import FirebaseAI
import ComposeApp

public class AIClientImpl: NSObject {
    private let model: GenerativeModel
    
    public override init() {
        let ai = FirebaseAI.firebaseAI(backend: .googleAI())
        self.model = ai.generativeModel(modelName: "gemini-2.0-flash-lite")
        super.init()
    }
}

extension AIClientImpl: AIClient {
    
    public func summarizeNote(
        noteContent: String,
        summaryType: SummaryType,
        configClient: ConfigClient
    ) async throws -> String {
        
        let systemPrompt = try await configClient.getSummaryPrompt(summaryType: summaryType)
        
        let fullPrompt = """
        \(systemPrompt)
        
        【メモ内容】
        \(noteContent)
        """
        
        let response = try await withTimeout(seconds: 30) {
            try await self.model.generateContent(fullPrompt)
        }
        
        return response.text ?? "要約の生成に失敗しました。"
    }
}

DI統合の仕組み

Android - Koinモジュールでの直接登録

// composeApp/src/androidMain/kotlin/com/example/notekeeper/di/AndroidModule.kt
val androidModule = module {
    // AI Client - Android implementation
    single<AIClient> { AIClientImpl() }
    
    // Config Client - Android implementation
    single<ConfigClient> { ConfigClientImpl() }
    
    // Auth Client - Android implementation
    single<AuthClient> { AuthClientImpl(androidContext()) }
    
    // Sync Service - Android implementation
    single<SyncService> { SyncServiceImpl() }
}

Androidでは、Kotlin actual実装をKoinモジュールに直接登録します。

iOS - SwiftインスタンスのKoin DI注入

iOSでは、SwiftでFirebase SDKを使った実装を作成し、それをKotlinのKoin DIに注入する2段階のアプローチを取ります。

Step 1: SwiftでFirebase実装を作成

// iosApp/iosApp/AppDelegate.swift
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
    ) -> Bool {
        
        // Firebase設定
        FirebaseApp.configure()
        
        // Swiftで各Firebase実装のインスタンスを作成
        let syncService = SyncServiceImpl()
        let aiClient = AIClientImpl()
        let configClient = ConfigClientImpl()
        let authClient = AuthClientImpl()
        
        // Kotlin KoinにSwift実装を注入
        InitKoinIosKt.doInitKoinIos(
            syncService: syncService,
            aiClient: aiClient,
            configClient: configClient,
            authClient: authClient
        )
        
        return true
    }
}

Step 2: Kotlin側でSwift実装をKoinモジュールに登録

// composeApp/src/iosMain/kotlin/com/example/notekeeper/di/IOSModule.kt
fun iosModule(
    syncService: SyncService,
    aiClient: AIClient,
    configClient: ConfigClient,
    authClient: AuthClient
) = module {
    // AI Client (Swift実装を注入)
    single<AIClient> { aiClient }
    
    // Config Client (Swift実装を注入)
    single<ConfigClient> { configClient }
    
    // Auth Client (Swift実装を注入)
    single<AuthClient> { authClient }
    
    // Sync Service (Swift実装を注入)
    single<SyncService> { syncService }
}

この仕組みにより、Kotlin側からはget<AIClient>()のようにKoin DIを通じて透過的にSwift実装を利用できます。

まとめ

Compose MultiplatformでFirebaseを統合する際、本アプローチには以下のメリットがあります:

  1. 最新機能への即座なアクセス: ネイティブSDKを直接使用するため、Firebase AIなどの最新機能をすぐに利用可能
  2. プラットフォーム最適化: Android/iOSそれぞれのベストプラクティスを活用
  3. 型安全性: SwiftとKotlin双方の型システムを活かしたコード品質
  4. 柔軟性: ラッパーライブラリの制約を受けず、必要な機能を自由に実装

一方、各プラットフォームで実装を維持する必要があるため、小規模プロジェクトや迅速なプロトタイピングでは既存のKMP Firebaseライブラリも選択肢となります。プロジェクトの要件に応じて最適なアプローチを選択してください。


CheerDailyでは本記事で紹介したアーキテクチャを採用しており、実際のプロダクション環境で安定稼働しています。本記事が、Compose MultiplatformでのFirebase統合の参考になれば幸いです。ぜひアプリもお試しください!

Discussion