Scott Whitman
08/28/2021, 1:26 PMlouiscad
08/28/2021, 1:48 PMshareIn
on it.Scott Whitman
08/28/2021, 2:18 PMshareIn
, but it requires a CoroutineScope. The class I am in doesn't have/need a CoroutineScope for anything else and I prefer not adding one as a dependency. I can also pass in a CoroutineScope as a function argument, but I would prefer to use a val
instead of a fun
for my library API if possible.
public val sharedFlow: SharedFlow<Int> = TODO("some hot flow")
public val mappedSharedFlow: SharedFlow<String> = sharedFlow.map { int ->
int.toString()
}.shareIn(
scope = TODO("I need a CoroutineScope here"),
started = SharingStarted.Lazily,
replay = 0
)
public fun mapSharedFlow(coroutineScope: CoroutineScope): SharedFlow<String> = sharedFlow.map { int ->
int.toString()
}.shareIn(
scope = coroutineScope,
started = SharingStarted.Lazily,
replay = 0
)
// This doesn't seem to work
public suspend fun mapSharedFlow(): SharedFlow<String> = coroutineScope {
return@coroutineScope sharedFlow.map { int ->
int.toString()
}.shareIn(
scope = this,
started = SharingStarted.Lazily,
replay = 0
)
}
I have tried to write a sharedMap
utility function but have been unsuccessful so far.louiscad
08/28/2021, 2:19 PMlouiscad
08/28/2021, 2:20 PMlouiscad
08/28/2021, 2:20 PMScott Whitman
08/28/2021, 3:45 PMprivate fun <T, R> SharedFlow<T>.mapShared(transform: suspend (T) -> R): SharedFlow<R> {
val context: CoroutineContext = TODO("Is there a way to get the context from the SharedFlow<T>?")
val coroutineScope = CoroutineScope(context)
return map(transform).shareIn(
scope = coroutineScope,
started = SharingStarted.Lazily,
)
}
louiscad
08/28/2021, 3:46 PMSharedFlow
.Scott Whitman
08/28/2021, 3:53 PMonSubscribed {}
has access to a coroutineContext but I don't think that helps here. It looks like I'll pass in an external CoroutineScope like fun mapSharedFlow(coroutineScope: CoroutineScope): SharedFlow<String> {...}