iTranslated by AI
How to Share Responses Received via Kotlin Flow
When using master data for screen display and wanting to refer to it again later, you might write something like this:
private val request = repository.getRepo("sobaya-0141")
init {
// Display on screen
request.onEach {
it.body()?.forEach {
print(it)
}
}.launchIn(viewModelScope)
}
// When a button is pressed
fun getRepos() {
viewModelScope.launch {
request.firstOrNull {
it?.body()?.forEach {
print(it.name)
}
true
}
}
}
If you build it like this, (obviously) the communication will run twice, which is wasteful.
Especially when retrieving large amounts of data, it becomes a significant waste.
I will introduce a solution for such cases.
ShareIn Version
ViewModel
private val request = repository.getRepo("sobaya-0141")
private val res = request.shareIn(viewModelScope, SharingStarted.Eagerly, 0)
init {
res.onEach {
it.body()?.forEach {
print(it)
}
}.launchIn(viewModelScope)
}
fun getRepos() {
viewModelScope.launch {
res.firstOrNull {
it?.body()?.forEach {
print(it.name)
}
true
}
}
}
In the sample above, compared to the first implementation, a variable called res was created using shareIn.
Also, both the init and getRepos methods now refer to res instead of request.
Now, the information retrieved in init at startup can also be obtained in the getRepos method.
Essentially, by applying shareIn to a Flow, you receive a SharedFlow.
About the arguments of ShareIn
You can specify Eagerly or Lazily for SharingStarted.
The difference is that Eagerly starts sharing immediately, while Lazily starts sharing when someone subscribes.
For the replay where I specified 0, I don't fully understand it yet because I haven't tracked SharedFlow well.
replay is a setting to keep the last N values.
If it's 1, it remembers the previous value, so the latest value can be obtained even if you start subscribing after it has been emitted.
StateIn Version
private val request = repository.getRepo("sobaya-0141")
private val res = request.stateIn(viewModelScope, SharingStarted.Eagerly, null)
init {
res.onEach {
it?.body()?.forEach {
print(it)
}
}.launchIn(viewModelScope)
}
fun getRepos() {
res.onEach {
it?.body()?.forEach {
print(it)
}
}.launchIn(viewModelScope)
}
Arguments of StateIn
Similar to ShareIn, you can specify Eagerly or Lazily for SharingStarted.
The difference here is that you also need to specify an initial value.
Conclusion
I don't fully understand SharedFlow yet, but if you want to share values within your own class like this time, I think StateFlow (stateIn) might be better.
I'll probably update and correct this after studying more.
Sample Project
Discussion