package com.gyf.lib.util import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.room.* /** * 登陆令牌 */ @Entity data class Token( @PrimaryKey val id: Int, @ColumnInfo val token: String, @ColumnInfo val createTime: Long ) data class OnlyToken( override val clientType: ClientType ) : ClientBaseVo() @Dao interface TokenDao { @Query("select * from token") suspend fun queryAll(): List @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun save(token: Token) @Delete suspend fun delete(user: Token) @Query("delete from token") suspend fun deleteAll() } object TokenManager { private var ownInfo: OwnInfoVo? = null private lateinit var personInfo: PersonInfoVo fun init(ownInfo: OwnInfoVo) { this.ownInfo = ownInfo when (ownInfo) { is ManagerVo -> this.personInfo = ManagerInfoVo( duty = ownInfo.duty, name = ownInfo.name, headImg = ownInfo.headImg, desc = ownInfo.desc ) is UserVo -> this.personInfo = UserInfoVo(name = ownInfo.name, headImg = ownInfo.headImg, desc = ownInfo.desc) else -> throw IllegalArgumentException("token失败") } } fun clear() { ownInfo = null } fun getOwnInfo(): OwnInfoVo { return ownInfo ?: throw IllegalArgumentException("token没有初始化,非法调用") } fun getPersonInfo(): PersonInfoVo { return personInfo } fun getToken(): Token { return ownInfo?.token ?: throw IllegalArgumentException("token没有初始化,非法调用") } } @Database(entities = [Token::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun tokenDao(): TokenDao private val mIsDatabaseCreated = MutableLiveData() /** * 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 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() } } }