I have a MutableStateFlow<String> which pass...
# coroutines
d
I have a MutableStateFlow<String> which passes an argument to a suspend fun. On each latest one I want to launch a suspend fun on the IO dispatcher, however if it emits a new value before the previous suspend function is complete, it should cancel that one and launch the suspend fun with the new argument. How should I do this?
would it be something like this?
Copy code
init {
    CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
        searchText.collectLatest {
            chunkedRank(it, assetIndex, 10)
        }
    }
}
☝️ 2
i
we did it like this:
Copy code
class TaskSearchDelegate(
    private val repository: TaskRepository,
) : SearchDelegate<TaskModel> {

    override lateinit var searchPagingFlow: Flow<PagingData<TaskModel>>

    private lateinit var uiCaller: UiCallerImpl
    private val searchTextFlow = MutableStateFlow("")

    override fun init(uiCaller: UiCallerImpl) {
        this.uiCaller = uiCaller
        searchPagingFlow = searchTextFlow.debounce(SearchDelegate.debounceDelayMs)
            .flatMapLatest {
                repository.searchTasks(it)
            }.cachedIn(uiCaller.scope)
    }

    override fun searchByText(text: String) {
        searchTextFlow.value = text
    }
}