Kotlin流发出但未接收到收集

huangapple go评论92阅读模式
英文:

Kotlin flow emits but collect is not receiving

问题

我有这个基本的流发射/收集代码,但收集部分没有接收到任何发射。

  1. object TodoRepository {
  2. fun getTodos(): Flow<List<Todo>> = flow {
  3. val data = KtorClient.httpClient.use {
  4. it.get("...")
  5. }
  6. val todos = data.body<List<Todo>>()
  7. emit(todos) // << emit 被调用
  8. }.flowOn(Dispatchers.IO)
  9. }
  10. class TodoViewModel: ViewModel() {
  11. val response = MutableSharedFlow<List<Todo>>()
  12. init {
  13. viewModelScope.launch {
  14. TodoRepository.getTodos().collect {
  15. // 从未被调用!!!
  16. response.emit(it)
  17. }
  18. }
  19. }
  20. }
  21. class MainActivity: AppCompatActivity() {
  22. private val todoViewModel: TodoViewModel by viewModels()
  23. override fun onCreate(savedInstanceState: Bundle?) {
  24. super.onCreate(savedInstanceState)
  25. setContentView(R.layout.activity_main)
  26. runBlocking {
  27. todoViewModel.response.collect {
  28. }
  29. }
  30. }
  31. }
英文:

I have this basic flow emit / collect code but collect is not receiving any emits.

  1. object TodoRepository {
  2. fun getTodos(): Flow&lt;List&lt;Todo&gt;&gt; = flow {
  3. val data = KtorClient.httpClient.use {
  4. it.get(&quot;...&quot;)
  5. }
  6. val todos = data.body&lt;List&lt;Todo&gt;&gt;()
  7. emit(todos) // &lt;&lt; emit is called
  8. }.flowOn(Dispatchers.IO)
  9. }
  10. class TodoViewModel: ViewModel() {
  11. val response = MutableSharedFlow&lt;List&lt;Todo&gt;&gt;()
  12. init {
  13. viewModelScope.launch {
  14. TodoRepository.getTodos().collect {
  15. // NEVER INVOKED !!!
  16. response.emit(it)
  17. }
  18. }
  19. }
  20. }
  21. class MainActivity: AppCompatActivity() {
  22. private val todoViewModel: TodoViewModel by viewModels()
  23. override fun onCreate(savedInstanceState: Bundle?) {
  24. super.onCreate(savedInstanceState)
  25. setContentView(R.layout.activity_main)
  26. runBlocking {
  27. todoViewModel.response.collect {
  28. }
  29. }
  30. }
  31. }

答案1

得分: 0

感谢 @Tenfour04 的评论。runBlocking 是问题所在。例如,以下代码将有效:

  1. CoroutineScope(Dispatchers.Main).launch {
  2. todoViewModel.response.collect {
  3. }
  4. }
英文:

Thanks to @Tenfour04 comment. runBlocking was the problem. For example, this will work

  1. CoroutineScope(Dispatchers.Main).launch {
  2. todoViewModel.response.collect {
  3. }
  4. }

huangapple
  • 本文由 发表于 2023年1月9日 04:12:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定