You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.5 KiB

package com.gyf.csams.util
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.room.*
import kotlinx.serialization.Serializable
/**
* 登陆令牌
*/
@Entity
@Serializable
data class Token(
@PrimaryKey val studentId: String,
@ColumnInfo val token: String,
@ColumnInfo val createTime: Long
)
/**
* 令牌传输
*
* @property isValid
* @property token
*/
@Serializable
data class TokenResDto(val isValid: Boolean, val token: Token?)
@Dao
interface TokenDao {
@Query("select * from token")
suspend fun queryAll(): List<Token>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun save(token: Token)
@Delete
suspend fun delete(user: Token)
}
class TokenManager private constructor(private var token: Token?) {
companion object {
@Volatile
private var instance: TokenManager? = null
fun getInstance(token: Token? = null) =
instance ?: synchronized(this) {
instance ?: TokenManager(token).also { instance = it }
}
}
}
@Database(entities = [Token::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun tokenDao(): TokenDao
private val mIsDatabaseCreated = MutableLiveData<Boolean>()
/**
* Check whether the database already exists and expose it via [.getDatabaseCreated]
*/
private fun updateDatabaseCreated(context: Context) {
if (context.getDatabasePath(DATABASE_NAME).exists()) {
setDatabaseCreated()
}
}
private fun setDatabaseCreated() {
mIsDatabaseCreated.postValue(true)
}
val databaseCreated: LiveData<Boolean>
get() = mIsDatabaseCreated
companion object {
private var sInstance: AppDatabase? = null
const val DATABASE_NAME = "basic-sample-db"
fun getInstance(context: Context): AppDatabase? {
if (sInstance == null) {
synchronized(AppDatabase::class.java) {
if (sInstance == null) {
sInstance =
buildDatabase(context.applicationContext)
sInstance!!.updateDatabaseCreated(context.applicationContext)
}
}
}
return sInstance
}
private fun buildDatabase(appContext: Context): AppDatabase {
return Room.databaseBuilder(appContext, AppDatabase::class.java, DATABASE_NAME)
.build()
}
}
}