如何在KMM项目iOS端调用共享模块的Apollo Client登录方法?
解决KMM中iOS端调用ApolloClient登录方法的线程错误
关键问题分析
你的崩溃主要来自三个核心问题:自定义类名与Apollo库类名冲突、iOS端直接调用Kotlin suspend函数的线程适配错误、网络请求未指定正确的后台调度器。以下是具体修复步骤:
1. 修正共享模块的核心代码
首先重命名自定义类避免与Apollo库的ApolloClient冲突,并为iOS添加专用异步调用接口:
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext data class User(val email: String?, val password: String?) // 重命名自定义类,避免和Apollo库的ApolloClient类冲突 class GraphQLClient { private val apolloClient = com.apollographql.apollo3.ApolloClient.Builder() .serverUrl("http://10.0.2.2:4000/graphql") .build() // 为iOS创建专用协程作用域,确保线程调度安全 private val iosCoroutineScope = kotlinx.coroutines.CoroutineScope(Dispatchers.Main + SupervisorJob()) // 核心suspend登录方法,指定IO调度器执行网络请求 suspend fun loginUser(email: String, password: String): User = withContext(Dispatchers.IO) { val response = apolloClient.query(LoginUserWithEmailAndPasswordQuery(email = email, password = password)).execute() val userEmail = response.data?.loginUser?.email val userPassword = response.data?.loginUser?.password User(userEmail, userPassword) } // iOS专用异步调用接口,用闭包返回结果 fun loginUserForIOS(email: String, password: String, completion: (Result<User>) -> Unit) { iosCoroutineScope.launch { try { val user = loginUser(email, password) completion(Result.success(user)) } catch (e: Exception) { completion(Result.failure(e)) } } } }
2. iOS端正确调用异步接口
修改iOS代码,使用包装后的异步方法,避免直接调用suspend函数:
import shared private var graphQLClient = GraphQLClient() // 在合适的业务逻辑中调用登录方法 graphQLClient.loginUserForIOS(email: "your_email", password: "your_password") { result in switch result { case .success(let user): // 处理登录成功逻辑 print("登录成功:\(user.email ?? "无邮箱")") case .failure(let error): // 处理登录失败逻辑 print("登录出错:\(error.localizedDescription)") } }
3. 确认共享模块依赖配置
确保build.gradle.kts(共享模块)中已添加正确的协程和Apollo依赖:
kotlin { sourceSets { val commonMain by getting { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3") implementation("com.apollographql.apollo3:apollo-runtime:3.8.2") } } val iosMain by getting { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3") } } } }
内容的提问来源于stack exchange,提问作者Luluxlu
相关产品推荐
相关产品推荐

