forked from android/compose-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReplyHomeViewModel.kt
85 lines (76 loc) · 2.81 KB
/
ReplyHomeViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.reply.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.reply.data.Email
import com.example.reply.data.EmailsRepository
import com.example.reply.data.EmailsRepositoryImpl
import com.example.reply.ui.utils.ReplyContentType
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
class ReplyHomeViewModel(private val emailsRepository: EmailsRepository = EmailsRepositoryImpl()) :
ViewModel() {
// UI state exposed to the UI
private val _uiState = MutableStateFlow(ReplyHomeUIState(loading = true))
val uiState: StateFlow<ReplyHomeUIState> = _uiState
init {
observeEmails()
}
private fun observeEmails() {
viewModelScope.launch {
emailsRepository.getAllEmails()
.catch { ex ->
_uiState.value = ReplyHomeUIState(error = ex.message)
}
.collect { emails ->
/**
* We set first email selected by default for first App launch in large-screens
*/
_uiState.value = ReplyHomeUIState(
emails = emails,
selectedEmail = emails.first()
)
}
}
}
fun setSelectedEmail(emailId: Long, contentType: ReplyContentType) {
/**
* We only set isDetailOnlyOpen to true when it's only single pane layout
*/
val email = uiState.value.emails.find { it.id == emailId }
_uiState.value = _uiState.value.copy(
selectedEmail = email,
isDetailOnlyOpen = contentType == ReplyContentType.SINGLE_PANE
)
}
fun closeDetailScreen() {
_uiState.value = _uiState
.value.copy(
isDetailOnlyOpen = false,
selectedEmail = _uiState.value.emails.first()
)
}
}
data class ReplyHomeUIState(
val emails: List<Email> = emptyList(),
val selectedEmail: Email? = null,
val isDetailOnlyOpen: Boolean = false,
val loading: Boolean = false,
val error: String? = null
)