-
Notifications
You must be signed in to change notification settings - Fork 629
/
AutocompleteViewModel.kt
245 lines (223 loc) · 8.46 KB
/
AutocompleteViewModel.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package com.stripe.android.paymentsheet.addresselement
import android.app.Application
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.stripe.android.paymentsheet.PaymentSheet
import com.stripe.android.paymentsheet.R
import com.stripe.android.paymentsheet.addresselement.analytics.AddressLauncherEventReporter
import com.stripe.android.ui.core.injection.NonFallbackInjectable
import com.stripe.android.paymentsheet.injection.AutocompleteViewModelSubcomponent
import com.stripe.android.ui.core.elements.SimpleTextFieldConfig
import com.stripe.android.ui.core.elements.SimpleTextFieldController
import com.stripe.android.ui.core.elements.TextFieldIcon
import com.stripe.android.ui.core.elements.autocomplete.PlacesClientProxy
import com.stripe.android.ui.core.elements.autocomplete.model.AutocompletePrediction
import com.stripe.android.ui.core.elements.autocomplete.model.transformGoogleToStripeAddress
import com.stripe.android.ui.core.injection.NonFallbackInjector
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.lang.IllegalStateException
import javax.inject.Inject
import javax.inject.Provider
internal class AutocompleteViewModel @Inject constructor(
val args: AddressElementActivityContract.Args,
val navigator: AddressElementNavigator,
private val placesClient: PlacesClientProxy?,
private val autocompleteArgs: Args,
private val eventReporter: AddressLauncherEventReporter,
application: Application
) : AndroidViewModel(application) {
private val _predictions = MutableStateFlow<List<AutocompletePrediction>?>(null)
val predictions: StateFlow<List<AutocompletePrediction>?>
get() = _predictions
private val _loading = MutableStateFlow(false)
val loading: StateFlow<Boolean>
get() = _loading
@VisibleForTesting
val addressResult = MutableStateFlow<Result<AddressDetails?>?>(null)
private val config = SimpleTextFieldConfig(
label = R.string.address_label_address,
trailingIcon = MutableStateFlow(null)
)
val textFieldController = SimpleTextFieldController(config)
private val queryFlow = textFieldController.fieldValue
.map { it }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), "")
private val debouncer = Debouncer()
init {
debouncer.startWatching(
coroutineScope = viewModelScope,
queryFlow = queryFlow,
onValidQuery = {
viewModelScope.launch {
placesClient?.findAutocompletePredictions(
query = it,
country = autocompleteArgs.country
?: throw IllegalStateException("Country cannot be empty"),
limit = MAX_DISPLAYED_RESULTS
)?.fold(
onSuccess = {
_loading.value = false
_predictions.value = it.autocompletePredictions
},
onFailure = {
_loading.value = false
addressResult.value = Result.failure(it)
}
)
}
}
)
viewModelScope.launch {
queryFlow.collect {
if (it.isEmpty()) {
config.trailingIcon.update {
null
}
} else {
config.trailingIcon.update {
TextFieldIcon.Trailing(
idRes = R.drawable.stripe_ic_clear,
isTintable = true,
onClick = { clearQuery() }
)
}
}
}
}
autocompleteArgs.country?.let { country ->
eventReporter.onShow(country)
}
}
fun selectPrediction(prediction: AutocompletePrediction) {
viewModelScope.launch {
_loading.value = true
placesClient?.fetchPlace(
placeId = prediction.placeId
)?.fold(
onSuccess = {
_loading.value = false
val address = it.place.transformGoogleToStripeAddress(getApplication())
addressResult.value = Result.success(
AddressDetails(
address = PaymentSheet.Address(
city = address.city,
country = address.country,
line1 = address.line1,
line2 = address.line2,
postalCode = address.postalCode,
state = address.state
)
)
)
setResultAndGoBack()
},
onFailure = {
_loading.value = false
addressResult.value = Result.failure(it)
setResultAndGoBack()
}
)
}
}
fun onBackPressed() {
val result = if (queryFlow.value.isNotBlank()) {
AddressDetails(
address = PaymentSheet.Address(
line1 = queryFlow.value
)
)
} else {
null
}
setResultAndGoBack(result)
}
fun onEnterAddressManually() {
setResultAndGoBack(
AddressDetails(
address = PaymentSheet.Address(
line1 = queryFlow.value
)
)
)
}
private fun setResultAndGoBack(addressDetails: AddressDetails? = null) {
if (addressDetails != null) {
navigator.setResult(AddressDetails.KEY, addressDetails)
} else {
addressResult.value?.fold(
onSuccess = {
navigator.setResult(AddressDetails.KEY, it)
},
onFailure = {
navigator.setResult(AddressDetails.KEY, null)
}
)
}
navigator.onBack()
}
private fun clearQuery() {
textFieldController.onRawValueChange("")
}
internal class Debouncer {
private var searchJob: Job? = null
fun startWatching(
coroutineScope: CoroutineScope,
queryFlow: StateFlow<String?>,
onValidQuery: (String) -> Unit
) {
coroutineScope.launch {
queryFlow.collect { query ->
query?.let {
searchJob?.cancel()
if (query.length > MIN_CHARS_AUTOCOMPLETE) {
searchJob = launch {
delay(SEARCH_DEBOUNCE_MS)
if (isActive) {
onValidQuery(it)
}
}
}
}
}
}
}
}
internal class Factory(
private val injector: NonFallbackInjector,
private val args: Args,
private val applicationSupplier: () -> Application
) : ViewModelProvider.Factory, NonFallbackInjectable {
@Inject
lateinit var subComponentBuilderProvider:
Provider<AutocompleteViewModelSubcomponent.Builder>
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
injector.inject(this)
return subComponentBuilderProvider.get()
.application(applicationSupplier())
.configuration(args)
.build().autoCompleteViewModel as T
}
}
data class Args(
val country: String?
)
companion object {
const val SEARCH_DEBOUNCE_MS = 1000L
const val MAX_DISPLAYED_RESULTS = 4
const val MIN_CHARS_AUTOCOMPLETE = 3
}
}