我对调度程序在 Kotlin 中的工作方式感到困惑
任务在我的应用程序类中,我打算通过 Room 访问我的数据库,取出用户,取出他的 JWT accessToken 并将其设置在我的改造请求受体使用的另一个对象中。
但是我希望所有这些代码都是阻塞的,以便当应用程序类运行到完成时,用户已被提取并在 Inteceptor 中设置。
问题我的应用程序类在从数据库中选取用户之前运行完成。
会话类是访问房间的类
这就是我的会话类的样子
class Session(private val userRepository: UserRepository, private var requestHeaders: RequestHeaders) {
var authenticationState: AuthenticationState = AuthenticationState.UNAUTHENTICATED
var loggedUser: User? by Delegates.observable<User?>(null) { _, _, user ->
if (user != null) {
user.run {
loggedRoles = roleCsv.split(",")
loggedRoles?.run {
if (this[0] == "Employer") {
employer = toEmployer()
} else if (this[0] == "Employee") {
employee = toEmployee()
}
}
authenticationState = AuthenticationState.AUTHENTICATED
requestHeaders.accessToken = accessToken
}
} else {
loggedRoles = null
employer = null
employee = null
authenticationState = AuthenticationState.UNAUTHENTICATED
requestHeaders.accessToken = null
}
}
var loggedRoles: List<String>? = null
var employee: Employee? = null
var employer: Employer? = null
init {
runBlocking(Dispatchers.IO) {
loggedUser = userRepository.loggedInUser()
Log.d("Session","User has been set")
}
}
// var currentCity
// var currentLanguage
}
enum class AuthenticationState {
AUTHENTICATED, // Initial state, the user needs to secretQuestion
UNAUTHENTICATED, // The user has authenticated successfully
LOGGED_OUT, // The user has logged out.
}
这是我的应用程序类
class MohreApplication : Application()
{
private val session:Session by inject()
private val mohreDatabase:MohreDatabase by inject() // this is integral. Never remove this from here. This seeds the data on database creation
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@MohreApplication)
modules(listOf(
platformModule,
networkModule,
....
))
}
Log.d("Session","Launching application")
}
创建会话的我的 Koin 模块
val platformModule = module {
// single { Navigator(androidApplication()) }
single { Session(get(),get()) }
single { CoroutineScope(Dispatchers.IO + Job()) }
}
在我的 Logcat 中,首先打印出"启动应用程序",然后"用户已设置">
不应该是反转吗?.这导致我的应用程序在没有会话有用户的情况下启动,并且我的主活动投诉。
by inject()
使用的是 Kotlin 延迟初始化。只有当查询session.loggedUser
时,才会触发init
块。
在您的情况下,当您在 MainActivity 中调用session.loggedUser
时,init
块将触发并阻止调用线程。
你能做的是。
import org.koin.android.ext.android.get
class MohreApplication : Application()
{
private lateinit var session: Session
private lateinit var mohreDatabase: MohreDatabase // this is integral. Never remove this from here. This seeds the data on database creation
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@MohreApplication)
modules(listOf(
platformModule,
networkModule,
....
))
}
session = get()
mohreDatabase = get()
Log.d("Session","Launching application")
}