kevin.cianfarini
09/05/2019, 7:24 PMFlow
as the bridge between a VM and a fragment, how can I ensure that the callback I use for the flow is initialized before I need It? The way I'm approaching it now seems like an antipattern. private var loadedPosts: List<Post> = emptyList()
private lateinit var loadedPostsCallback: LoadedPostsCallback
val posts: Flow<List<Post>> = callbackFlow {
val callback = object : LoadedPostsCallback {
override fun setLoadedPosts(posts: List<Post>) {
loadedPosts = loadedPosts + posts
offer(loadedPosts)
}
}
loadedPostsCallback = callback
awaitClose()
}
posts
. However, the loadedPostsCallback
isn't initialized when I try to do the initial load from loadPosts()
.suspendCoroutine
until I can ensure everything is initialized correctly, but I feel like there's a better waycallbackFlow
and using a backing channel of my own made this easierDominaezzz
09/05/2019, 7:37 PMloadedPostsCallback
inside callbackFlow
?kevin.cianfarini
09/05/2019, 7:38 PMcollect
was being calledDominaezzz
09/05/2019, 7:51 PMproduceIn
and turn the flow into a channel.kevin.cianfarini
09/05/2019, 7:51 PMprivate val postsChannel: Channel<List<Post>> = Channel(CONFLATED)
val posts: Flow<List<Post>> = flow {
postsChannel.consumeEach {
loadedPosts = it
emit(it)
}
}
Channel.offer
as the callbackDominaezzz
09/05/2019, 7:55 PMkevin.cianfarini
09/05/2019, 7:56 PMDominaezzz
09/05/2019, 7:59 PMcallbackFlow {}.onEach {}.launchIn(coroutineScope)
.kevin.cianfarini
09/05/2019, 8:00 PMDominaezzz
09/05/2019, 8:02 PMloadedPostsCallback
be initialised and registered inside a flow? (Do you need a context or smth)kevin.cianfarini
09/05/2019, 8:07 PMDominaezzz
09/05/2019, 8:09 PMkevin.cianfarini
09/05/2019, 8:09 PM