1、修复小程序问题
This commit is contained in:
Elemt 2026-11-09 18:32:20 +08:00
parent 738fb2fe33
commit 158b71fa5e
15 changed files with 180 additions and 56 deletions

View File

@ -4,10 +4,10 @@
<selectionStates> <selectionStates>
<SelectionState runConfigName="app"> <SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" /> <option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2026-03-24T05:48:19.296324800Z"> <DropdownSelection timestamp="2026-11-09T09:16:20.249736600Z">
<Target type="DEFAULT_BOOT"> <Target type="DEFAULT_BOOT">
<handle> <handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=JRBI89BIE6AI5TG6" /> <DeviceId pluginId="PhysicalDevice" identifier="serial=Y5DELZR46DZTCI9D" />
</handle> </handle>
</Target> </Target>
</DropdownSelection> </DropdownSelection>

View File

@ -51,8 +51,8 @@ android {
applicationId = "com.img.rabbit" applicationId = "com.img.rabbit"
minSdk = 24 minSdk = 24
targetSdk = 37 targetSdk = 37
versionCode = 2 versionCode = 3
versionName = "1.0.1" versionName = "1.0.3"
multiDexEnabled = true multiDexEnabled = true
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"

View File

@ -13,6 +13,7 @@ import com.github.gzuliyujiang.oaid.DeviceID
import com.github.gzuliyujiang.oaid.IGetter import com.github.gzuliyujiang.oaid.IGetter
import com.img.rabbit.config.Constants import com.img.rabbit.config.Constants
import com.img.rabbit.provider.storage.PreferenceUtil import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.uni.UniMPImmersiveWindow
import com.img.rabbit.utils.ChannelUtils import com.img.rabbit.utils.ChannelUtils
import com.tencent.mmkv.MMKV import com.tencent.mmkv.MMKV
import com.umeng.analytics.MobclickAgent import com.umeng.analytics.MobclickAgent
@ -33,6 +34,8 @@ class BaseApplication : Application() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
// UniMP Activity 运行在独立进程,窗口适配必须在主进程判断之前注册。
UniMPImmersiveWindow.register(this)
// 只有是主进程时,才执行重量级初始化 // 只有是主进程时,才执行重量级初始化
if (getProcessName(this) == packageName) { if (getProcessName(this) == packageName) {
Log.i(TAG, "进行必要的SDK初始化...") Log.i(TAG, "进行必要的SDK初始化...")

View File

@ -1,11 +1,13 @@
package com.img.rabbit.bean.response package com.img.rabbit.bean.response
import com.google.gson.annotations.SerializedName import com.google.gson.annotations.SerializedName
import com.google.gson.annotations.JsonAdapter
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
@Serializable @Serializable
class ConfigEntity { class ConfigEntity {
@SerializedName("client.banner.home") //首页轮播图 @SerializedName("client.banner.home") //首页轮播图
@JsonAdapter(HomeBannerListAdapter::class)
var homeBanners: List<HomeBannerEntity?>? = emptyList() var homeBanners: List<HomeBannerEntity?>? = emptyList()
@SerializedName("client.version.upgrade") //版本更新 @SerializedName("client.version.upgrade") //版本更新
var versionEntity: VersionEntity? = null var versionEntity: VersionEntity? = null

View File

@ -1,10 +1,12 @@
package com.img.rabbit.bean.response package com.img.rabbit.bean.response
import com.google.gson.annotations.SerializedName
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
/** client.banner.home,与 flaunt-android 的 HomeBannerBean 字段一致。 */ /** client.banner.home,与 flaunt-android 的 HomeBannerBean 字段一致。 */
@Serializable @Serializable
data class HomeBannerEntity( data class HomeBannerEntity(
@SerializedName(value = "img", alternate = ["icon"])
val img: String? = null, val img: String? = null,
val url: String? = null, val url: String? = null,
val type: String? = null, val type: String? = null,

View File

@ -0,0 +1,23 @@
package com.img.rabbit.bean.response
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import java.lang.reflect.Type
/** 后端配置兼容单个 banner 对象和 banner 数组。 */
class HomeBannerListAdapter : JsonDeserializer<List<HomeBannerEntity?>> {
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext,
): List<HomeBannerEntity?> = when {
json.isJsonObject -> listOf(context.deserialize(json, HomeBannerEntity::class.java))
json.isJsonArray -> json.asJsonArray.map { item ->
context.deserialize<HomeBannerEntity?>(item, HomeBannerEntity::class.java)
}
json.isJsonNull -> emptyList()
else -> throw JsonParseException("client.banner.home must be an object or array")
}
}

View File

@ -3,7 +3,7 @@ package com.img.rabbit.config
object Constants { object Constants {
const val RELEASE_BASE_URL = "https://jitutu.batiao8.com" //release const val RELEASE_BASE_URL = "https://jitutu.batiao8.com" //release
const val DEBUG_BASE_URL = "https://jitutu.batiao8.com" //debug const val DEBUG_BASE_URL = "https://jitutu.batiao8.com" //debug
const val LOG_REQUEST = "RabbitRequest" const val LOG_REQUEST = "RequestLog"
const val agreementUrl = "https://jitutu.batiao8.com/static/policy-jietutu/user_android.html" //用户协议 const val agreementUrl = "https://jitutu.batiao8.com/static/policy-jietutu/user_android.html" //用户协议
const val privacyUrl = "https://jitutu.batiao8.com/static/policy-jietutu/provacy.html"//隐私政策 const val privacyUrl = "https://jitutu.batiao8.com/static/policy-jietutu/provacy.html"//隐私政策
@ -16,4 +16,4 @@ object Constants {
const val AESDecrypt = "e4rOtnF8tJjtHO7ecZeJHN1rapED5ImB" //解密 const val AESDecrypt = "e4rOtnF8tJjtHO7ecZeJHN1rapED5ImB" //解密
const val Signature = "xn08hYoizXhZ1zHP8DVqfCm2yHxPmhil" //加密字符 const val Signature = "xn08hYoizXhZ1zHP8DVqfCm2yHxPmhil" //加密字符
} }

View File

@ -140,15 +140,14 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
bottomBar = { bottomBar = {
if (isNavigationBarVisible) { if (isNavigationBarVisible) {
Column( Column(
modifier = Modifier.navigationBarsPadding() modifier = Modifier
.background(Color.White)
.navigationBarsPadding()
) { ) {
Box(modifier = Modifier.height(52.dp)) { Box(modifier = Modifier.height(52.dp)) {
NavigationBar( NavigationBar(
containerColor = if (selectedTab == TabItem.Mine) { containerColor = Color.White,
Color(0xFFF9F9F9) tonalElevation = 0.dp,
} else {
Color.White
},
contentColor = Color.Transparent contentColor = Color.Transparent
) { ) {
tabItems.forEachIndexed { index, item -> tabItems.forEachIndexed { index, item ->
@ -359,4 +358,4 @@ fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewMode
} }
} }
} }
} }

View File

@ -22,10 +22,8 @@ import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@ -57,7 +55,6 @@ import com.img.rabbit.utils.GlobalEventBus
import com.img.rabbit.viewmodel.GeneralViewModel import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel import com.img.rabbit.viewmodel.LoginViewModel
import com.img.rabbit.viewmodel.MineViewModel import com.img.rabbit.viewmodel.MineViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
/** /**
@ -75,7 +72,7 @@ fun MineScreen(
val context = LocalContext.current val context = LocalContext.current
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
//用户数据 //用户数据
var userInfo by remember { mutableStateOf(PreferenceUtil.getUserInfo()) } val userInfo by loginViewModel.userInfo
// 获取当前路由状态 // 获取当前路由状态
val navBackStackEntry by navController.currentBackStackEntryAsState() val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route val currentRoute = navBackStackEntry?.destination?.route
@ -92,15 +89,6 @@ fun MineScreen(
} }
} }
LaunchedEffect(loginViewModel.userInfoResult.value) {
if(loginViewModel.userInfoResult.value != null){
// 等待200ms,确保用户配置已经刷新
delay(200)
userInfo = PreferenceUtil.getUserInfo()
}
}
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@ -622,4 +610,4 @@ private fun doLogin(generalViewModel: GeneralViewModel, navController: NavHostCo
@Composable @Composable
private fun PreviewMineScreen(){ private fun PreviewMineScreen(){
MineScreen(navController = rememberNavController(), loginViewModel = viewModel(), generalViewModel = viewModel()) MineScreen(navController = rememberNavController(), loginViewModel = viewModel(), generalViewModel = viewModel())
} }

View File

@ -2,6 +2,7 @@
package com.img.rabbit.provider.api package com.img.rabbit.provider.api
import android.util.Log
import com.batiao.batiaosdk.SignInterceptor import com.batiao.batiaosdk.SignInterceptor
import com.img.rabbit.BuildConfig import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants import com.img.rabbit.config.Constants
@ -10,6 +11,7 @@ import com.img.rabbit.provider.utils.ResponseInterceptor
import com.img.rabbit.provider.utils.getUnsafeOkHttpClient import com.img.rabbit.provider.utils.getUnsafeOkHttpClient
import com.img.rabbit.viewmodel.`interface`.ServiceVo import com.img.rabbit.viewmodel.`interface`.ServiceVo
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
@ -39,6 +41,7 @@ object ApiManager {
.readTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(HeaderInterceptor()) .addInterceptor(HeaderInterceptor())
.addDebugRequestLogging()
.addInterceptor(SignInterceptor) .addInterceptor(SignInterceptor)
.build() .build()
@ -56,6 +59,7 @@ object ApiManager {
.writeTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(HeaderInterceptor()) .addInterceptor(HeaderInterceptor())
.addInterceptor(ResponseInterceptor()) .addInterceptor(ResponseInterceptor())
.addDebugRequestLogging()
.addInterceptor(SignInterceptor) .addInterceptor(SignInterceptor)
.build() .build()
@ -71,6 +75,19 @@ object ApiManager {
} }
} }
private fun OkHttpClient.Builder.addDebugRequestLogging(): OkHttpClient.Builder = apply {
if (BuildConfig.DEBUG) {
// 放在签名拦截器外侧,以记录 SDK 解密后的响应。
addInterceptor(HttpLoggingInterceptor { message ->
message.chunked(1000).forEach { chunk ->
Log.d(Constants.LOG_REQUEST, chunk)
}
}.apply {
level = HttpLoggingInterceptor.Level.BODY
})
}
}
// 添加重新初始化方法,用于在baseUrl改变时调用 // 添加重新初始化方法,用于在baseUrl改变时调用
fun reinitialize() { fun reinitialize() {
// 重置所有实例,使其在下一次访问时重新初始化 // 重置所有实例,使其在下一次访问时重新初始化

View File

@ -132,7 +132,7 @@ object PreferenceUtil {
fun saveUserInfo(userInfoEntity: UserInfoEntity?) { fun saveUserInfo(userInfoEntity: UserInfoEntity?) {
if(userInfoEntity == null){ if(userInfoEntity == null){
mmkv.encode(KEY_USER_INFO, gson.toJson("{}")) mmkv.remove(KEY_USER_INFO)
}else{ }else{
mmkv.encode(KEY_USER_INFO, gson.toJson(userInfoEntity)) mmkv.encode(KEY_USER_INFO, gson.toJson(userInfoEntity))
} }
@ -140,7 +140,8 @@ object PreferenceUtil {
fun getUserInfo(): UserInfoEntity? { fun getUserInfo(): UserInfoEntity? {
return try { return try {
gson.fromJson(mmkv.decodeString(KEY_USER_INFO, "{}"), UserInfoEntity::class.java) gson.fromJson(mmkv.decodeString(KEY_USER_INFO, null), UserInfoEntity::class.java)
?.takeIf { !it.user_id.isNullOrBlank() }
}catch (e: Exception){ }catch (e: Exception){
null null
} }
@ -209,4 +210,4 @@ object PreferenceUtil {
fun clearAll() { fun clearAll() {
mmkv.clearAll() mmkv.clearAll()
} }
} }

View File

@ -1,11 +1,9 @@
package com.img.rabbit.provider.utils package com.img.rabbit.provider.utils
import android.util.Log
import com.github.gzuliyujiang.oaid.DeviceIdentifier import com.github.gzuliyujiang.oaid.DeviceIdentifier
import com.img.rabbit.provider.storage.PreferenceUtil import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.BuildConfig import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants import com.img.rabbit.config.Constants
import com.img.rabbit.config.Constants.LOG_REQUEST
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
import com.img.rabbit.provider.utils.HeadParamUtils.getAppVersionName import com.img.rabbit.provider.utils.HeadParamUtils.getAppVersionName
import com.img.rabbit.utils.ChannelUtils import com.img.rabbit.utils.ChannelUtils
@ -33,22 +31,6 @@ class HeaderInterceptor : Interceptor {
mBuilder.header("x-click-id", "${ChannelUtils.getBdVid(applicationContext)}") mBuilder.header("x-click-id", "${ChannelUtils.getBdVid(applicationContext)}")
mBuilder.header("x-app-id", Constants.AppId) mBuilder.header("x-app-id", Constants.AppId)
val stringBuilder = StringBuilder()
stringBuilder.append("-------------> 📤 header start<-------------\n")
stringBuilder.append("│ x-token = $accessToken\n")
stringBuilder.append("│ x-version = ${getAppVersionName()}\n")
stringBuilder.append("│ x-device-id = ${DeviceIdentifier.getAndroidID(applicationContext)}\n")
stringBuilder.append("│ x-mobile-brand = ${android.os.Build.BRAND}\n")
stringBuilder.append("│ x-mobile-model = ${android.os.Build.MODEL}\n")
stringBuilder.append("│ x-base-version = ${getAppVersionName()}\n")
stringBuilder.append("│ x-channel = ${ChannelUtils.getChannel(applicationContext)}\n")
stringBuilder.append("│ x-click-id = ${ChannelUtils.getBdVid(applicationContext)}\n")
stringBuilder.append("│ x-package = ${BuildConfig.APPLICATION_ID}\n")
stringBuilder.append("-------------> header end <-------------")
Log.i(LOG_REQUEST, stringBuilder.toString())
val request = mBuilder val request = mBuilder
.method(original.method, original.body) .method(original.method, original.body)
.build() .build()
@ -72,4 +54,4 @@ class HeaderInterceptor : Interceptor {
return chain.proceed(original) return chain.proceed(original)
} }
} }
} }

View File

@ -0,0 +1,95 @@
package com.img.rabbit.uni
import android.app.Activity
import android.app.Application
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import android.view.Window
import android.view.WindowManager
import io.dcloud.feature.sdk.DCUniMPActivity
/** 在各 UniMP 进程中维持底部沉浸,覆盖启动图关闭、页面切换和后台返回。 */
@Suppress("DEPRECATION")
object UniMPImmersiveWindow {
fun register(application: Application) {
application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
private val controllers = mutableMapOf<Activity, Controller>()
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
// 包含 DCUniMPActivity0..4 和 DCUniMPTopActivity0..4;不改宿主及支付等页面。
if (activity is DCUniMPActivity) {
controllers[activity] = Controller(activity.window)
}
}
override fun onActivityResumed(activity: Activity) {
controllers[activity]?.apply()
}
override fun onActivityDestroyed(activity: Activity) {
controllers.remove(activity)?.close()
}
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
})
}
internal fun apply(window: Window) {
val flags = window.attributes.flags
if (flags and WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS == 0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
}
if (flags and WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION != 0) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
if (window.navigationBarColor != Color.TRANSPARENT) window.navigationBarColor = Color.TRANSPARENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && window.navigationBarDividerColor != Color.TRANSPARENT) {
window.navigationBarDividerColor = Color.TRANSPARENT
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && window.isNavigationBarContrastEnforced) {
window.isNavigationBarContrastEnforced = false
}
// 只让内容延伸至导航栏下方。保留 SDK 的状态栏、图标颜色和 adjustResize 输入法处理;
// 不隐藏系统手势条,也不消费键盘或状态栏的 WindowInsets。
val decor = window.decorView
val visibility = decor.systemUiVisibility or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
if (decor.systemUiVisibility != visibility) decor.systemUiVisibility = visibility
}
private class Controller(private val window: Window) :
ViewTreeObserver.OnGlobalLayoutListener, ViewTreeObserver.OnWindowFocusChangeListener {
private val decor = window.decorView
private val observer = decor.viewTreeObserver
init {
observer.addOnGlobalLayoutListener(this)
observer.addOnWindowFocusChangeListener(this)
apply()
}
fun apply() = UniMPImmersiveWindow.apply(window)
override fun onGlobalLayout() = apply()
override fun onWindowFocusChanged(hasFocus: Boolean) {
if (hasFocus) apply()
}
fun close() {
// 未附着时注册的 ViewTreeObserver 会合并到附着后的 observer。
val activeObserver = if (observer.isAlive) observer else decor.viewTreeObserver
if (activeObserver.isAlive) {
activeObserver.removeOnGlobalLayoutListener(this)
activeObserver.removeOnWindowFocusChangeListener(this)
}
}
}
}

View File

@ -9,8 +9,9 @@ import android.view.View
import android.view.ViewTreeObserver import android.view.ViewTreeObserver
import android.view.WindowManager import android.view.WindowManager
import androidx.core.view.WindowCompat import androidx.core.view.WindowCompat
import io.dcloud.feature.sdk.DCUniMPActivity
/** 只在 UniMP 启动图显示期间让图片延伸到系统导航栏下方。 */ /** 启动图期间设置导航图标明暗,关闭后交由 UniMP 正文的沉浸控制器接管。 */
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
class UniMPSplashWindow( class UniMPSplashWindow(
context: Context, context: Context,
@ -19,7 +20,8 @@ class UniMPSplashWindow(
) : ) :
View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener { View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener {
private val window = findActivity(context)?.window private val activity = findActivity(context)
private val window = activity?.window
private val originalNavigationBarColor = window?.navigationBarColor private val originalNavigationBarColor = window?.navigationBarColor
private val originalSystemUiVisibility = window?.decorView?.systemUiVisibility ?: 0 private val originalSystemUiVisibility = window?.decorView?.systemUiVisibility ?: 0
private val originalWindowFlags = window?.attributes?.flags ?: 0 private val originalWindowFlags = window?.attributes?.flags ?: 0
@ -81,7 +83,7 @@ class UniMPSplashWindow(
fun close() { fun close() {
if (closed) return if (closed) return
closed = true closed = true
// 先取消监听及延时任务,防止关闭后再次改动小程序正文的窗口。 // 先取消启动图监听及延时任务,正文由独立的沉浸控制器维护。
splashView.removeCallbacks(reapply) splashView.removeCallbacks(reapply)
splashView.removeOnAttachStateChangeListener(this) splashView.removeOnAttachStateChangeListener(this)
observer?.takeIf { it.isAlive }?.removeOnGlobalLayoutListener(this) observer?.takeIf { it.isAlive }?.removeOnGlobalLayoutListener(this)
@ -100,6 +102,8 @@ class UniMPSplashWindow(
originalContrastEnforced?.let { window.isNavigationBarContrastEnforced = it } originalContrastEnforced?.let { window.isNavigationBarContrastEnforced = it }
} }
insetsController?.isAppearanceLightNavigationBars = originalLightNavigationBars insetsController?.isAppearanceLightNavigationBars = originalLightNavigationBars
// 启动图关闭时立即接续底部沉浸,避免恢复窗口后先露出一帧安全区底色。
if (activity is DCUniMPActivity) UniMPImmersiveWindow.apply(window)
} }
private companion object { private companion object {

View File

@ -86,8 +86,9 @@ class LoginViewModel : BaseViewModel() {
// 保留最新配置供首页观察;userConfigResult 作为请求完成事件会被 Activity 清空。 // 保留最新配置供首页观察;userConfigResult 作为请求完成事件会被 Activity 清空。
private val _userConfig = mutableStateOf(PreferenceUtil.getUserConfig()) private val _userConfig = mutableStateOf(PreferenceUtil.getUserConfig())
val userConfig: State<UserConfigEntity?> = _userConfig val userConfig: State<UserConfigEntity?> = _userConfig
// 用户信息获取结果 // 页面直接观察用户数据,缓存只用于首次加载。
val userInfoResult = mutableStateOf<ResultVo<UserInfoEntity>?>(null) private val _userInfo = mutableStateOf(PreferenceUtil.getUserInfo())
val userInfo: State<UserInfoEntity?> = _userInfo
// 错误状态 // 错误状态
val errorState = mutableStateOf<ErrorBean?>(null) val errorState = mutableStateOf<ErrorBean?>(null)
@ -385,12 +386,18 @@ class LoginViewModel : BaseViewModel() {
} }
fun requestUserInfo(){ fun requestUserInfo(){
PreferenceUtil.saveUserInfo(null) val currentUserId = _userConfig.value?.user_id
if (!currentUserId.isNullOrBlank() && _userInfo.value?.user_id != currentUserId) {
PreferenceUtil.saveUserInfo(null)
_userInfo.value = null
}
mLaunch { mLaunch {
val response = ApiManager.serviceVo.userInfo() val response = ApiManager.serviceVo.userInfo()
// 切换账号后,忽略旧账号尚未完成的请求。
if (currentUserId != _userConfig.value?.user_id) return@mLaunch
if(response.status){ if(response.status){
PreferenceUtil.saveUserInfo(response.data) PreferenceUtil.saveUserInfo(response.data)
userInfoResult.value = response _userInfo.value = response.data
} }
} }
} }
@ -405,6 +412,7 @@ class LoginViewModel : BaseViewModel() {
val response = ApiManager.serviceVo.logout() val response = ApiManager.serviceVo.logout()
if (response.status) { if (response.status) {
PreferenceUtil.clearLogin() PreferenceUtil.clearLogin()
_userInfo.value = null
AppEventBus.post( LoginBindEvent.Login(userId = null, loginType = PreferenceUtil.getLoginType(), isLogin = false, data = null) ) AppEventBus.post( LoginBindEvent.Login(userId = null, loginType = PreferenceUtil.getLoginType(), isLogin = false, data = null) )
} else { } else {
errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "退出登录失败" }) errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "退出登录失败" })