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.
99 lines
2.4 KiB
99 lines
2.4 KiB
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
|
|
)
|
|
|
|
abstract class ClientBaseVo {
|
|
abstract val token: Token
|
|
abstract val clientType: ClientType
|
|
}
|
|
|
|
abstract class BaseToken {
|
|
abstract val token: Token
|
|
}
|
|
|
|
data class OnlyToken(
|
|
override val token: Token = TokenManager.token ?: throw IllegalArgumentException("无法获取token"),
|
|
override val clientType: ClientType
|
|
) : ClientBaseVo()
|
|
|
|
@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)
|
|
|
|
@Query("delete from token")
|
|
suspend fun deleteAll()
|
|
}
|
|
|
|
object TokenManager {
|
|
var token: Token? = null
|
|
|
|
}
|
|
|
|
|
|
@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()
|
|
}
|
|
|
|
|
|
}
|
|
} |