Last active
October 27, 2023 23:52
-
-
Save djleeds/716f3acbd94b8e4367ab66ba403778d7 to your computer and use it in GitHub Desktop.
Simple example demonstrating how you might be able to use a delegated property with a flow in Kotlin, in response to a comment on YouTube here: https://www.youtube.com/watch?v=KFgb6l1PUJI&lc=Ugy1TJWi4MwXZOtTGOF4AaABAg. Warning - I'm not very experienced with Flow at this point, so there might be a better way to do this!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.collect | |
import kotlinx.coroutines.flow.flow | |
import kotlinx.coroutines.flow.onEach | |
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.runBlocking | |
import kotlin.properties.ReadOnlyProperty | |
import kotlin.reflect.KProperty | |
fun createFlow(): Flow<Int> = flow { | |
for (i in 1..100) { | |
delay(100) | |
emit(i) | |
} | |
} | |
fun main() = runBlocking<Unit> { | |
val latest by FlowLatest(createFlow(), 0, this) | |
launch { | |
for (i in 1..40) { | |
delay(250) | |
println(latest) | |
} | |
} | |
} | |
class FlowLatest<T>(flow: Flow<T>, initial: T, scope: CoroutineScope) : ReadOnlyProperty<Any?, T> { | |
private var latest: T = initial | |
init { | |
scope.launch { flow.onEach { latest = it }.collect() } | |
} | |
override fun getValue(thisRef: Any?, property: KProperty<*>): T = latest | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment