只要确定用户的身份验证状态,我就想创建一个启动画面并显示它。我有一个全局singleton
调用AuthStateController
,它保存我的状态和一些额外的功能。
但是因为该installSplashScreen
函数在可组合之外,所以我不能使用 Koin 注入AuthStateController
类来访问我的loading
状态。
下面是我的 MainActivity 和我所有的 Koin 模块。和installSplashScreen
功能。
class MainActivity : ComponentActivity() {
// not allowed because outside of Composable
private val authStateController: AuthStateController by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startKoin {
androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE)
androidContext(this@MainActivity)
modules(listOf(appModule, networkModule, viewModelModule, interactorsModule))
}
installSplashScreen().apply {
setKeepVisibleCondition {
// need AuthStateController instance to determine loading state
authStateController.state.value.isLoading
}
}
setContent {
M3Theme {
SetupNavGraph()
}
}
}
}
}
module
这是提供我的课程的 Koin AuthStateController
:
val appModule = module {
single { AuthStateController(get()) }
}
这是我的AuthStateController
类,它包含我的状态和一些额外的功能:
class AuthStateController(
private val getMeInterceptor: GetMeInterceptor
) {
val state: MutableState<AuthState> = mutableStateOf(AuthState())
fun fetchMe() {
val me = getMeInterceptor.execute().collect(CoroutineScope(Dispatchers.IO)) { dataState ->
dataState.data?.let {
state.value =
state.value.copy(profile = it, isAuthenticated = true, isLoading = false)
}
}
}
init {
val token = settings.getString(Constants.AUTH_TOKEN)
if (token.isNotBlank()) {
fetchMe()
state.value = state.value.copy(authToken = token)
}
}
}
如何singleton
在 MainActivity 中访问用 Koin 创建的并在installSplashScreen
函数中使用它?
编辑
安卓清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.sessions_clean.android">
<uses-permission android:name="android.permission.INTERNET" />
<application
// app crashes when adding line below
android:name=".MainApplication"
android:allowBackup="false"
android:supportsRtl="true"
android:theme="@style/Theme.App.Starting"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/Theme.App.Starting">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
当我添加android:name
到已经存在的应用程序标签时,应用程序会立即崩溃。
但是当我为新的应用程序标签创建一个新的应用程序标签时,MainApplication
我在 IDE 中遇到错误,比如Attribute android:allowBackup is not allowed here