init
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package com.sw.inbound.viewmodel
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.sw.inbound.GlobalKey
|
||||
import com.sw.inbound.model.request.LoginParam
|
||||
import com.sw.inbound.model.response.User
|
||||
import com.sw.inbound.repository.RemoteRepository
|
||||
import com.sw.inbound.utils.GsonUtils
|
||||
import com.sw.inbound.utils.SPUtil
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class UserViewModel @Inject constructor(
|
||||
private val repo: RemoteRepository
|
||||
) : BaseViewModel(repo) {
|
||||
|
||||
private var isFirstLaunch by mutableStateOf(true)
|
||||
|
||||
private val _user = MutableStateFlow<User?>(null)
|
||||
val user = _user.asStateFlow()
|
||||
|
||||
fun getInitInfo() {
|
||||
Timber.d("getInitInfo isFirstLaunch = $isFirstLaunch")
|
||||
if (isFirstLaunch) {
|
||||
|
||||
getUserInfo()
|
||||
getDictType()
|
||||
isFirstLaunch = false
|
||||
}
|
||||
}
|
||||
|
||||
fun login(userName: String, password: String) = launchWithLoading {
|
||||
val loginParam = LoginParam(userName = userName, password = password)
|
||||
val response = repo.login(loginParam)
|
||||
if (response.isSuccess()) {
|
||||
_user.value = response.data
|
||||
saveToken(response.data)
|
||||
response.data?.token
|
||||
}
|
||||
}
|
||||
|
||||
fun getUserInfo() {
|
||||
val userInfo = SPUtil.getInstance().get(GlobalKey.KEY_USER_INFO, "")
|
||||
if (userInfo != null) {
|
||||
_user.value = GsonUtils.fromJson(userInfo, User::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveToken(user: User?) {
|
||||
user?.let {
|
||||
SPUtil.getInstance().put(GlobalKey.KEY_USER_INFO, GsonUtils.toJson(it))
|
||||
SPUtil.getInstance().put(GlobalKey.KEY_TOKEN, it.token)
|
||||
}
|
||||
}
|
||||
|
||||
fun logout() {
|
||||
SPUtil.getInstance().remove(GlobalKey.KEY_USER_INFO)
|
||||
SPUtil.getInstance().remove(GlobalKey.KEY_TOKEN)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user