Sam Stone
07/16/2023, 9:03 PMsuspend fun getValue(): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
if(condition) {
return@withContext CONST
} else {
if(disk.readValueFromDisk() == "") {
val newValue = Generator.generateValue().toString()
disk.writeValueToDisk(newValue)
}
return@withContext disk.readValueFromDisk()
}
}
B:
suspend fun getValue(): String = if(condition) CONST else withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
disk
.readValueFromDisk()
.takeIf { it.isNotEmpty() }
?: Generator
.generateValue()
.toString()
.also {
disk.writeValueToDisk(it)
}
}
Joffrey
07/16/2023, 9:20 PMwithContext
unnecessarily, so if you have a condition where it's not useful to switch threads, don't. A second thing is about storing the value you read from disk. In B, you use functional operators and read only once. In A, you don't use functional operators, but that doesn't mean you can't store the result you read in a variable