https://kotlinlang.org logo
#konsist
Title
# konsist
e

Emanuel Moecklin

10/16/2023, 6:17 PM
We're experimenting with rules to enforce some company standards (22 Android devs) and so far I love it (especially compared with custom Lint rules...). One of the rules we want to enforce is that Fragments need to use
viewLifecycleOwner.lifecycleScope
over
lifecycleScope
to launch a Coroutine so
Copy code
// BAD
lifecycleScope.launch {
    // here goes my code
}

// GOOD
viewLifecycleOwner.lifecycleScope.launch {
    // here goes my code
}
Unfortunately both add the same import so I can't check for imports. Any ideas how this could be done?
❤️ 1
y

Yonatan Karp-Rudin

10/16/2023, 8:19 PM
I don't know a single thing about android, but have you considered using something like the code snippet suggested in the docs?
Copy code
@Test
fun `coroutine scope usage of 'lifecycleScope.launch' in file is forbiden`() {
    Konsist
        .scopeFromProject()
        .files
        .assertFalse { it.text.contains("lifecycleScope.launch") }
}
You can see the original example here.
❤️ 1
e

Emanuel Moecklin

10/16/2023, 8:49 PM
ah yes that might work... let me test that thank you color
💯 1
To limit this to certain classes I will use
Copy code
// matches `lifecycleScope.launch` but doesn't match `viewLifecycleOwner.lifecycleScope.launch`
private val launchRegex = "[^\\.]+lifecycleScope\\.launch".toRegex()

Konsist
    .scopeFromProject()
    .classes()
    .withAllParentsOf(Fragment::class)
    .assertFalse {
        it.text.contains(launchRegex)
    }
💯 1
👍 1
🙂 1
i

igor.wojda

10/17/2023, 8:55 AM
BTW @Emanuel Moecklin we would like to add more Android snippets to our docs. Consider sharing some of your tests in the future when you will come up with interesting examples.
👍 1