https://kotlinlang.org logo
Title
f

Florian

09/02/2021, 12:42 PM
I get that I should not hardcode dispatchers in my repos, viewmodels, etc. But what if I want to switch Dispatcher in an extension function of some data class?
suspend fun List<TaskStatistic>.getCurrentCompletedStreak(): Int =
    withContext(Dispatchers.Default) {
        var currentStreak = 0
        for (statistic in this@getCurrentCompletedStreak.reversed()) {
            if (!statistic.taskCompleted) break
            currentStreak++
        }
        currentStreak
    }
r

Richard Gomez

09/02/2021, 1:07 PM
Two thoughts: 1. You could use
coroutineScope { }
to inherit the calling scope/context 2. This is something that multiple receivers will alleviate
f

Florian

09/02/2021, 1:11 PM
i feel like my design must be wrong because I don't like either of those options
coroutineScope doesn't switch the thread, right? So I might as well leave it out
d

Dominaezzz

09/02/2021, 3:24 PM
Does that need to be a suspend function? Let the caller decide I think.
Also there's an
indexOf { }
operator btw.
f

Florian

09/02/2021, 3:56 PM
ok makes sense
what are you referring to with indexOf?
d

Dominaezzz

09/02/2021, 3:57 PM
To replace the for loop.
f

Florian

09/02/2021, 8:35 PM
ok, thank you
e

eygraber

09/03/2021, 12:49 AM
You can also pass a Dispatcher to the function, which is mostly the same as letting the caller decide, but it allows you to be more targeted about what goes on that dispatcher (e.g. if you only want a specific section of the function to go there)
👍 1
f

Florian

09/03/2021, 2:16 PM
yea it just feels weird to declare dispatcher arguments for these functions
1