英文:
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<List<Todo>> = flow {
val data = KtorClient.httpClient.use {
it.get("...")
}
val todos = data.body<List<Todo>>()
emit(todos) // << emit is called
}.flowOn(Dispatchers.IO)
}
class TodoViewModel: ViewModel() {
val response = MutableSharedFlow<List<Todo>>()
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 {
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论