Is there a way for handling loss of items If a Mut...
# coroutines
r
Is there a way for handling loss of items If a MutableStateFlow which is emitting from background thread faster than the subscriber can collect in main thread?. Using .value to set the value and copying the value from previous state value.
l
You want to use
buffer()
for these collectors. You might also want to use
MutableSharedFlow
instead.
r
But if the collection happens after the emit is complete shared flow wont store any value right and collector wont receive anything Right ?
l
The question is a bit complex to answer properly for me, but I think you'd better off testing stuff to validate your understanding of the doc of StateFlow, MutableStateFlow, SharedFlow, MutableSharedFlow, how emit is actually calling the lambda passed to collect and suspends until it's complete, and the buffer operator.
r
I have this view model
Copy code
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

class someviewmodel @Inject constructor() : ViewModel() {
    private val _test = MutableSharedFlow<String>()
    val test: SharedFlow<String>
        get() = _test.asSharedFlow()

    private fun check() {
        someFun(
            call1 = {
                viewModelScope.launch {
                    _test.emit(it)
                }
            },
            call2 = {
                viewModelScope.launch {
                    _test.emit(it)
                }
            }
        )
    }

    private fun someFun(call1: (s1: String) -> Unit, call2: (s2: String) -> Unit) {
        call1("hello")
        call2("morning")
    }

    fun loadCheck() {
        check()
    }
}
And this Screen in compose where i am collecting
Copy code
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.hilt.navigation.compose.hiltViewModel
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.collect

@InternalCoroutinesApi
@Composable
fun SomeScreen(
    viewModel: someviewmodel = hiltViewModel(),
) {

    LaunchedEffect(true){
        Log.d("Ravin", "LaunchedEffect")
        viewModel.test.buffer().collect { 
            Log.d("Here", "here $it")
        }
    }

    LaunchedEffect(Unit){
        viewModel.loadCheck()
    }

}
In the logs i dont see this log at all
Copy code
Log.d("Here", "here $it")
Am i missing something here
l
I'm on mobile, I won't read the snippet FYI
I'd test without compose, and without Android first, just to check my understanding without involving interop with other parts
🙏 1