Search code examples
androidkotlinkotlin-coroutineskotlin-flowkotlin-stateflow

collect flow doesn't receive value from repository/usecase in viewmodel - android coroutines


I have a Repository + UseСase + ViewModel + MVI architecture.

I have a UseCase for collecting Flow, and another UseCase to update Flow in repository When I go to the screen, collect fires and gives me the initial value, which is correct, but then, when I call UseCase to update my flow in the repostory - the ViewModel no longer collects any data, although they were definitely updated there, no the code in collect doesn't work. What could be the problem?

interface Repository {

    val flow: Flow<List<Int>>

    suspend fun filter(ids: List<Int>)
}

internal class RepositoryImpl(
    ///
) : Repository {

    private val _flow = MutableStateFlow<List<Int>>(emptyList())
    override val flow: Flow<List<Int>> = _flow.asStateFlow()

    override suspend fun filter(ids: List<Int>) {
        _flow.emit(ids)
    }
}

internal class UseCaseImpl(
    private val repository: Repository
) : UseCase {

    override val propertyIds: Flow<List<Int>> = repository.flow
}

interface UseCase {

    val propertyIds: Flow<List<Int>>
}

interface FilterUseCase {

    suspend operator fun invoke(ids: List<Int>)
}

internal class FilterUseCaseImpl(
    private val repository: Repository
) : FilterUseCase {

    override suspend fun invoke(ids: List<Int>) {
        repository.filter(ids)
    }
}

class ViewModel: BaseViewModel<State, Event, Effect>() {

    private val filterUseCase: FilterUseCase by inject()
    private val useCase: UseCase by inject()

    init {
        viewModelScope.launch {
            useCase.propertyIds.collect {
                //
            }
        }
    }

    override fun setInitialState(): State = State()

    override fun handleEvents(event: Event) {
        when (event) {
            is Event.OnCheckedProperty -> viewModelScope.launch {
                val ids = state.value.propertyIds.keys.map { it }
                filterUseCase(ids)
            }
        }
    }
}

Solution

  • Is your repository/data source a singleton? One of the cases is that you have different sources of data. Make sure there is a single source.