Skip to content

Commit 4b3932f

Browse files
stefanosianoshanamatthews
authored andcommitted
Add Android sample for Regex on main thread (#7490)
* Add example code to offload regex check off the main thread
1 parent 0972eb1 commit 4b3932f

File tree

1 file changed

+30
-0
lines changed
  • src/docs/product/issues/issue-details/performance-issues/regex-main-thread

1 file changed

+30
-0
lines changed

src/docs/product/issues/issue-details/performance-issues/regex-main-thread/index.mdx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,33 @@ DispatchQueue.global(qos: .userInitiated).async {
6262
}
6363
}
6464
```
65+
66+
### Android
67+
68+
The following code calls `String.matches` on the UI thread to search for matches against a regular expression in a large text:
69+
70+
```kotlin
71+
fun matchRegex(text: String, regexPattern: String) {
72+
val matches = text.matches(regexPattern.toRegex())
73+
if (matches) {
74+
// Do something
75+
}
76+
}
77+
```
78+
79+
Performance could be improved by moving the match to a coroutine:
80+
81+
```kotlin
82+
fun matchRegex(text: String, regexPattern: String) {
83+
lifecycleScope.launch(Dispatchers.Default) {
84+
val pattern = Pattern.compile(regexPattern)
85+
val matches = pattern.matcher(text).matches()
86+
87+
withContext(Dispatchers.Main) {
88+
if (matches) {
89+
// Do something
90+
}
91+
}
92+
}
93+
}
94+
```

0 commit comments

Comments
 (0)