Kotlin流发出但未接收到收集

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

Kotlin flow emits but collect is not receiving

问题

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

object TodoRepository {
    fun getTodos(): Flow<List<Todo>> = flow {
        val data = KtorClient.httpClient.use {
            it.get("...")
        }
        val todos = data.body<List<Todo>>()
        emit(todos) // << emit 被调用
    }.flowOn(Dispatchers.IO)
}

class TodoViewModel: ViewModel() {
    val response = MutableSharedFlow<List<Todo>>()

    init {
        viewModelScope.launch {
            TodoRepository.getTodos().collect {
                // 从未被调用!!!
                response.emit(it)
            }
        }
    }
}

class MainActivity: AppCompatActivity() {
    private val todoViewModel: TodoViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        runBlocking {
            todoViewModel.response.collect {
            }
        }
    }
}
英文:

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

object TodoRepository {
    fun getTodos(): Flow&lt;List&lt;Todo&gt;&gt; = flow {
        val data = KtorClient.httpClient.use {
            it.get(&quot;...&quot;)
        }
        val todos = data.body&lt;List&lt;Todo&gt;&gt;()
        emit(todos) // &lt;&lt; emit is called
    }.flowOn(Dispatchers.IO)
}

class TodoViewModel: ViewModel() {
    val response = MutableSharedFlow&lt;List&lt;Todo&gt;&gt;()

    init {
        viewModelScope.launch {
            TodoRepository.getTodos().collect {
                // NEVER INVOKED !!!
                response.emit(it)
            }
        }
    }
}

class MainActivity: AppCompatActivity() {
    private val todoViewModel: TodoViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        runBlocking {
            todoViewModel.response.collect {
            }
        }
    }
}

答案1

得分: 0

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

CoroutineScope(Dispatchers.Main).launch {
    todoViewModel.response.collect {
    }
}
英文:

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

    CoroutineScope(Dispatchers.Main).launch {
        todoViewModel.response.collect {
        }
    }

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:

确定