Skip to content

Commit b465b60

Browse files
committed
Use a deferred to await user decision instead of flow
1 parent 6bd6422 commit b465b60

File tree

1 file changed

+7
-14
lines changed

1 file changed

+7
-14
lines changed

sample-app/src/main/java/at/bitfire/cert4android/demo/MainActivity.kt

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ import androidx.lifecycle.viewModelScope
3838
import at.bitfire.cert4android.Cert4Android
3939
import at.bitfire.cert4android.CustomCertManager
4040
import at.bitfire.cert4android.CustomCertStore
41+
import kotlinx.coroutines.CompletableDeferred
4142
import kotlinx.coroutines.Dispatchers
4243
import kotlinx.coroutines.flow.MutableStateFlow
4344
import kotlinx.coroutines.flow.StateFlow
44-
import kotlinx.coroutines.flow.first
4545
import kotlinx.coroutines.launch
4646
import org.apache.http.conn.ssl.AllowAllHostnameVerifier
4747
import org.apache.http.conn.ssl.StrictHostnameVerifier
@@ -179,10 +179,10 @@ class MainActivity : ComponentActivity() {
179179
private val _certificateFlow = MutableStateFlow<X509Certificate?>(null)
180180
val certificateFlow: StateFlow<X509Certificate?> = _certificateFlow
181181

182-
private val _userDecisionFlow = MutableStateFlow<Boolean?>(null)
182+
private var userDecision: CompletableDeferred<Boolean> = CompletableDeferred()
183183

184184
fun setUserDecision(decision: Boolean) {
185-
_userDecisionFlow.value = decision
185+
userDecision.complete(decision)
186186
_certificateFlow.value = null
187187
}
188188

@@ -208,21 +208,14 @@ class MainActivity : ComponentActivity() {
208208
viewModelScope,
209209
trustSystemCerts = trustSystemCerts,
210210
getUserDecision = { cert ->
211-
// Called by cert4android to get user decision on whether to trust this certificate
212-
Log.i(Cert4Android.TAG, "getUserDecision(${cert.encoded}): ?")
211+
// Reset user decision
212+
userDecision = CompletableDeferred()
213213

214214
// Show TrustDecisionDialog with certificate to user
215215
_certificateFlow.value = cert
216216

217-
// ... wait for user decision and save it
218-
val userDecision: Boolean = _userDecisionFlow.first { it != null } == true
219-
220-
// ... reset user decision
221-
_userDecisionFlow.value = null
222-
223-
// return the decision to cert4android
224-
Log.i(Cert4Android.TAG, "getUserDecision(${cert.encoded}): $userDecision")
225-
userDecision
217+
// Wait for user decision and return it
218+
userDecision.await()
226219
}
227220
)
228221
urlConn.hostnameVerifier = certMgr.HostnameVerifier(StrictHostnameVerifier())

0 commit comments

Comments
 (0)