标签: coroutine

Python 生成器发送:发送后不产生新值

这是一个奇怪的问题,所以我将解释:

我有一个像这样的生成器,它充当 IRC 服务器的生成器前端:

def irc_iter(): # not the real code, simplified
    msgs = get_msgs()
    for msg in msgs:
        if is_ping(msg):
            pong()
        else:
            to_send = yield msg
            for s in to_send:
                send(s)
Run Code Online (Sandbox Code Playgroud)

从理论上讲,这应该允许我做一些很酷的事情,例如:

server = connect()
for line in server:
       if should_respond(line):
           server.send('WOW SUCH MESSAGE')
Run Code Online (Sandbox Code Playgroud)

但是,有一个问题:也会generator.send 产生下一个值。这意味着这server.send也给了我下一条消息......我更愿意像所有其他消息一样处理它,产生为line.

我知道我可以用一种丑陋的方式来解决这个问题,在接收到发送后只产生一个垃圾值,但我试图保持我的代码优雅,但恰恰相反。有没有办法告诉生成器我还不需要新值?

谢谢。

python yield generator yield-keyword coroutine

8
推荐指数
1
解决办法
1126
查看次数

Lua合作例程

我试图了解如何使用协同例程来"暂停"一个脚本并等待一些处理完成后再恢复.

也许我正在以错误的方式看待惯例.但我的尝试结构类似于这个答案中给出的例子.

循环loop.lua永远不会达到第二次迭代,因此永远不会达到i == 4退出C代码中的运行循环所需的条件.如果我不屈服loop.lua,则此代码按预期执行.

main.cpp中

#include <lua/lua.hpp>

bool running = true;

int lua_finish(lua_State *) {
    running = false;
    printf("lua_finish called\n");
    return 0;
}
int lua_sleep(lua_State *L) {
    printf("lua_sleep called\n");
    return lua_yield(L,0);
}

int main() {
    lua_State* L = lua_open();
    luaL_openlibs(L);

    lua_register(L, "sleep", lua_sleep);
    lua_register(L, "finish", lua_finish);

    luaL_dofile(L, "scripts/init.lua");

    lua_State* cL = lua_newthread(L);
    luaL_dofile(cL, "scripts/loop.lua");

    while (running) {
        int status;
        status = lua_resume(cL,0);
        if (status == LUA_YIELD) {
            printf("loop yielding\n");
        } else …
Run Code Online (Sandbox Code Playgroud)

c++ scripting lua coroutine

7
推荐指数
1
解决办法
4994
查看次数

如何处理改造和协程挂起的错误

我用 rxjava 构建了我的应用程序,需要转换为协程以进行后台工作我需要帮助才能看到使用改造 2.6.0 和协程的实际示例以及正确的错误处理方法,提前致谢

我尝试创建一个通用的错误处理程序进行改造,并为 Loading Authenticated Error 的网络资源状态创建一个包装器

class AuthRepository @Inject constructor(val authApi: AuthApi) {

    suspend fun Loginauth(email:String,password:String)= liveData {
        emit(AuthResource.loading(null))
        try{
            val response=authApi.login(email,password)
            if (response.isSuccessful){
                emit(AuthResource.authenticated(response.body()))
            }
            emit(AuthResource.error(response.message(),null))
        }catch (e:Throwable){
            Log.d("any","error occured ${e.message}")
         emit(AuthResource.error(e.message!!,null))
        }catch (e:HttpException){
            Log.d("any","error http error${e.message}")
            emit(AuthResource.error(e.message!!,null))
        }


    }



}
Run Code Online (Sandbox Code Playgroud)

我的视图模型类

       screenState.value= AuthResource.loading(null)
        viewModelScope.launch {
            val source=authRepository.Loginauth(email!!,password!!)
            screenState.addSource(source){
             AuthResource.authenticated(it)
                screenState.removeSource(source)
                if (it.status == AuthResource.AuthStatus.ERROR){
                    screenState.removeSource(source)
                    AuthResource.error(it.message!!,null)
                }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

android coroutine kotlin retrofit

7
推荐指数
0
解决办法
2060
查看次数

PyQt5 和 Asyncio

是否可以让 UDP 服务器作为异步函数运行,接收数据,然后将其传递给也作为异步函数运行的 (PyQt5) 小部件?

这个想法是,当进入服务器的数据更新时,它也会更新小部件。

我已经有一个简单的 UDP 服务器和一个(PyQt5)小部件,它们独立工作正常,但我正在努力尝试将它们组合起来并保持它们异步运行并交换数据(服务器将数据传输到小部件)

[更新]

下面是我正在尝试的一个小部件

import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow
import asyncio


class Speedometer(QMainWindow):

    angleChanged = QtCore.pyqtSignal(float)

    def __init__(self, parent = None):

        QtWidgets.QWidget.__init__(self, parent)

        self._angle = 0.0

        self._margins = 20

        self._pointText = {0: "40", 30: "50", 60: "60", 90: "70", 120: "80",
                           150:"" , 180: "", 210: "",
                          240: "0", 270: "10", 300: "20", 330: "30", 360: ""}
    def paintEvent(self, event):

        painter = QtGui.QPainter()
        painter.begin(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing) …
Run Code Online (Sandbox Code Playgroud)

python pyqt coroutine pyqt5 python-asyncio

7
推荐指数
1
解决办法
1万
查看次数

kotlin flow onEach 没有被触发

我正在尝试使用 来存储价值DataStore


class BasicDataStore(context: Context) :
    PrefsDataStore(
        context,
        PREF_FILE_BASIC
    ),
    BasicImpl {

    override val serviceRunning: Flow<Boolean>
        get() = dataStore.data.map { preferences ->
            preferences[SERVICE_RUNNING_KEY] ?: false
        }

    override suspend fun setServiceRunningToStore(serviceRunning: Boolean) {
        dataStore.edit { preferences ->
            preferences[SERVICE_RUNNING_KEY] = serviceRunning
        }
    }

    companion object {
        private const val PREF_FILE_BASIC = "basic_preference"
        private val SERVICE_RUNNING_KEY = booleanPreferencesKey("service_running")
    }
}

@Singleton
interface BasicImpl {
    val serviceRunning: Flow<Boolean>
    suspend fun setServiceRunningToStore(serviceRunning: Boolean)
}
Run Code Online (Sandbox Code Playgroud)

在 a 中Service,尝试监视该值,以下是相应的代码:

private fun monitorNotificationService() { …
Run Code Online (Sandbox Code Playgroud)

datastore coroutine kotlin kotlin-coroutines kotlin-flow

7
推荐指数
1
解决办法
3995
查看次数

为什么 co_await 不能返回字符串?

#include <coroutine>
#include <string>

template<typename T>
struct Awaiter final {
    bool await_ready() const { return false; }    
    void await_suspend(std::coroutine_handle<>) const {}    
    T await_resume() const { return T{}; }
};

struct ReturnObject {
  struct promise_type {
    ReturnObject get_return_object() { return {}; }
    std::suspend_never initial_suspend() 
        noexcept { return {}; }
    std::suspend_never final_suspend() 
        noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() {}
  };
};

ReturnObject f()
{
    auto a1 = Awaiter<int>{};
    [[maybe_unused]] auto v1 = co_await a1; // ok    
    auto a2 …
Run Code Online (Sandbox Code Playgroud)

c++ gcc compiler-errors coroutine c++20

7
推荐指数
1
解决办法
442
查看次数

将两个 kotlin 流合并为一个流,该流发出两个原始流的最新值?

如果我们有两个这样定义的流:

val someflow = flow {
    emit("something")
}
Run Code Online (Sandbox Code Playgroud)

另一个流程定义如下:

val stateFlow = MutableStateFlow("some value")
Run Code Online (Sandbox Code Playgroud)

是否可以将两个流组合成一个流,该流仅发出someflowor发出的最后一个值stateFlow

这个想法是,stateFlow可能会在未来的某个时刻发出一个值,但在那之前我只想要someflow最后发出的任何值。在“组合”流程中,我想只获取 发出的第一个值someflow,但随后能够观察 上的其余更新stateFlow

看起来这可以通过组合函数来完成,但我只想发出两个流之间的最新发出值,我不关心一个流的最后一个值是什么。

coroutine kotlin kotlin-coroutines kotlin-flow kotlin-stateflow

7
推荐指数
1
解决办法
8271
查看次数

Boost::Asio 和 C++20 协程之间有什么关系?

我开始尝试通过阅读文档和示例代码来学习 Boost::Asio 。我发现事情很难理解,特别是因为该模型看起来与协程相似。

然后我决定从这个cppcon 演讲开始学习协程。在链接的演讲中,在协程使用示例中给出了以下行。该示例是在 2014 年编写的,因此语法可能与 C++20 协程不匹配。

auto conn = await Tcp::connect.Read("127.0.0.1", 1337)
Run Code Online (Sandbox Code Playgroud)

这感觉与 Boost::Asio 的既定目标相似。然而,在 Boost::Asio 文档的示例部分,有一个混合了 Boost::Asio 和 C++20 协程的示例。(我还不明白这个例子。)

Boost::Asio 和协程有什么关系?协程会取代 Boost::Asio 的部分内容吗?如果我不从事网络工作,我还应该使用 Boost::Asio 吗?std::async发送者/接收者提案在哪里适合这一切?

c++ boost asynchronous coroutine boost-asio

7
推荐指数
1
解决办法
3175
查看次数

在广播接收器上运行协程函数

我正在制作一个闹钟应用程序,并使用 AlarmManager 来设置闹钟。在 AlarmManager 上运行 setAlarm 后,我使用 Room 保存每个闹钟,这样如果手机关闭,我可以稍后恢复它们。

我在设备启动后使用 Android 开发人员站点的指南运行 BroadcastReceiver: https: //developer.android.com/training/scheduling/alarms#boot

我的想法是通过 onReceive 方法从 Room 获取警报但是 Room 使用挂起乐趣来获取警报,但我无法在 onReceive 上运行它,因为 BroadcastReceiver 没有生命周期

我怎样才能达到类似的结果?

android coroutine broadcastreceiver kotlin

7
推荐指数
1
解决办法
4778
查看次数

我什么时候应该使用 asyncio.create_task?

我正在使用 Python 3.10,我对asyncio.create_task.

在下面的示例代码中,无论我是否使用asyncio.create_task. 似乎没有什么区别。

如何确定何时使用以及使用与不使用相比asyncio.create_task有何优势?asyncio.create_task

import asyncio
from asyncio import sleep

async def process(index: int):
    await sleep(1)
    print('ok:', index)

async def main1():
    tasks = []
    for item in range(10):
        tasks.append(asyncio.create_task(process(item)))
    await asyncio.gather(*tasks)

async def main2():
    tasks = []
    for item in range(10):
        tasks.append(process(item)) # Without asyncio.create_task
    await asyncio.gather(*tasks)

asyncio.run(main1())
asyncio.run(main2())
Run Code Online (Sandbox Code Playgroud)

python task coroutine python-3.x python-asyncio

7
推荐指数
1
解决办法
2014
查看次数