fix: better detection of logged state at startup (#550)

This commit is contained in:
Diego Beraldin 2024-02-25 10:42:57 +01:00 committed by GitHub
parent 7892b0ccf6
commit 4ddba1a5d7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 30 additions and 19 deletions

View File

@ -4,11 +4,10 @@ import com.github.diegoberaldin.raccoonforlemmy.core.persistence.repository.Acco
import com.github.diegoberaldin.raccoonforlemmy.core.utils.network.NetworkManager
import com.github.diegoberaldin.raccoonforlemmy.domain.lemmy.repository.SiteRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
internal class DefaultIdentityRepository(
@ -19,21 +18,7 @@ internal class DefaultIdentityRepository(
private val scope = CoroutineScope(SupervisorJob())
override val authToken = MutableStateFlow<String?>(null)
override val isLogged = authToken.map { authOrNull ->
if (authOrNull.isNullOrEmpty()) {
false
} else if (networkManager.isNetworkAvailable()) {
val currentUser = siteRepository.getCurrentUser(authOrNull)
currentUser != null
} else {
null
}
}.stateIn(
scope = scope,
initialValue = false,
started = SharingStarted.WhileSubscribed(5_000)
)
override val isLogged = MutableStateFlow<Boolean?>(null)
init {
scope.launch {
@ -43,14 +28,34 @@ internal class DefaultIdentityRepository(
} else {
authToken.value = ""
}
refreshLoggedState()
}
}
override fun storeToken(jwt: String) {
authToken.value = jwt
refreshLoggedState()
}
override fun clearToken() {
authToken.value = ""
isLogged.value = false
}
override fun refreshLoggedState() {
scope.launch(Dispatchers.IO) {
val auth = authToken.value.orEmpty()
if (auth.isEmpty()) {
isLogged.value = false
} else {
val newIsLogged = if (networkManager.isNetworkAvailable()) {
val currentUser = siteRepository.getCurrentUser(auth)
currentUser != null
} else {
null
}
isLogged.value = newIsLogged
}
}
}
}

View File

@ -12,4 +12,6 @@ interface IdentityRepository {
)
fun clearToken()
fun refreshLoggedState()
}

View File

@ -323,7 +323,8 @@ class PostListScreen : Screen {
}
items(
items = uiState.posts,
key = { it.id.toString() + (it.updateDate ?: it.publishDate) },
// isLogged is added to the key to force swipe action refresh
key = { it.id.toString() + (it.updateDate ?: it.publishDate) + uiState.isLogged },
) { post ->
LaunchedEffect(post.id) {
if (settings.markAsReadWhileScrolling && !post.read) {

View File

@ -249,6 +249,9 @@ class PostListViewModel(
hideReadPosts = false
updateState { it.copy(canFetchMore = true, refreshing = true) }
loadNextPage()
if (identityRepository.isLogged.value == null) {
identityRepository.refreshLoggedState()
}
}
private suspend fun loadNextPage() {