https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

zain

06/04/2021, 3:13 PM
How to make a list of objects as sharedFlow
Copy code
val players: SharedFlow<List<Player>>   = MutableSharedFlow(,Player("Messi"), Player("Ronaldo"))
Is it possible to collect the changes of a list of object if one item is changed or updated?
c

Charlie Christensen

06/04/2021, 3:16 PM
MutableSharedFlow(listOf(Player("Messi"), Player("Ronaldo")))
To update it you have to pass a new list to the shared flow
👍 1
z

zain

06/04/2021, 3:18 PM
It says it requires
Int
as it is expecting
Copy code
public fun <T> MutableSharedFlow(
    replay: Int = 0,
    extraBufferCapacity: Int = 0,
    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND
): MutableSharedFlow<T>
c

Charlie Christensen

06/04/2021, 3:20 PM
Oops I thought it was StateFlow
You can’t pass an initial value to MutableSharedFlow
z

zain

06/04/2021, 3:24 PM
Oh
Can't even do this,
Copy code
val players: Flow<List<Player>> = flow { listOf(Player("Messi"), Player("Ronaldo")) }.shareIn(
        viewModelScope,
        replay = 1,
        started = SharingStarted.WhileSubscribed()
    )
As it is shown over here,
Copy code
class NewsRemoteDataSource(...,
    private val externalScope: CoroutineScope,
) {
    val latestNews: Flow<List<ArticleHeadline>> = flow {
        ...
    }.shareIn(
        externalScope,
        replay = 1,
        started = SharingStarted.WhileSubscribed()
    )
}
Not enough information to infer type variable T
c

Charlie Christensen

06/04/2021, 3:35 PM
Copy code
val players: Flow<List<Player>> = flow { 
    emit(listOf(Player("Messi"), Player("Ronaldo"))) 
}.shareIn(
        viewModelScope,
        replay = 1,
        started = SharingStarted.WhileSubscribed()
)
In order to send the value to the Flow you have to
emit
it
z

zain

06/04/2021, 3:55 PM
Woah, any simple resource to learn flow?
3 Views