Skip to content

Commit

Permalink
Free focus inside a coroutine scope (#46)
Browse files Browse the repository at this point in the history
* Free focus inside a coroutine scope

Fixes #42

* Add back try/catch

* Reduce CyclomaticComplexity by moving code to a method
  • Loading branch information
ankur2136 authored Oct 11, 2023
1 parent b278af7 commit 5280bed
Showing 1 changed file with 17 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
Expand Down Expand Up @@ -56,6 +57,7 @@ import com.togitech.ccp.data.utils.getUserIsoCode
import com.togitech.ccp.data.utils.numberHint
import com.togitech.ccp.transformation.PhoneNumberTransformation
import kotlinx.collections.immutable.ImmutableSet
import kotlinx.coroutines.launch

private val DEFAULT_TEXT_FIELD_SHAPE = RoundedCornerShape(24.dp)
private const val TAG = "TogiCountryCodePicker"
Expand Down Expand Up @@ -157,6 +159,8 @@ fun TogiCountryCodePicker(
)
}

val coroutineScope = rememberCoroutineScope()

OutlinedTextField(
value = phoneNumber,
onValueChange = { enteredPhoneNumber ->
Expand Down Expand Up @@ -187,11 +191,8 @@ fun TogiCountryCodePicker(
)
onValueChange(country.countryPhoneCode to phoneNumber.text, isNumberValid)
keyboardController?.hide()
// https://github.com/jump-sdk/jetpack_compose_country_code_picker_emoji/issues/42
try {
focusRequester.freeFocus()
} catch (exception: IllegalStateException) {
Log.e(TAG, "Unable to free focus", exception)
coroutineScope.launch {
freeFocus(focusRequester)
}
},
focusRequester = focusRequester,
Expand Down Expand Up @@ -256,7 +257,9 @@ fun TogiCountryCodePicker(
keyboardActions = keyboardActions ?: KeyboardActions(
onDone = {
keyboardController?.hide()
focusRequester.freeFocus()
coroutineScope.launch {
freeFocus(focusRequester)
}
},
),
singleLine = true,
Expand All @@ -265,6 +268,14 @@ fun TogiCountryCodePicker(
)
}

private fun freeFocus(focusRequester: FocusRequester) {
try {
focusRequester.freeFocus()
} catch (exception: IllegalStateException) {
Log.e(TAG, "Unable to free focus", exception)
}
}

@Composable
private fun PlaceholderNumberHint(countryIso: Iso31661alpha2) {
Text(
Expand Down

0 comments on commit 5280bed

Please sign in to comment.