这是一个奇怪的问题,所以我将解释:
我有一个像这样的生成器,它充当 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.
我知道我可以用一种丑陋的方式来解决这个问题,在接收到发送后只产生一个垃圾值,但我试图保持我的代码优雅,但恰恰相反。有没有办法告诉生成器我还不需要新值?
谢谢。
我正在探索在Android UI线程的上下文中使用协同例程.我contextJob按照Coroutines Guide UI中的描述实现了.后台工作从GUI开始,我想在每次点击时重新启动它(停止当前运行的并重新启动它).
但是一旦被取消的工作就无法重复使用,所以甚至创造了一份儿童工作:
val job = Job(contextJob)
Run Code Online (Sandbox Code Playgroud)
并取消它并没有帮助,因为它必须被重新分配.
有没有办法重用Job实例?
我正在使用 discord.py 库构建一个 discord bot - 因此所有用户交互都必须在协程中进行,使用 async 定义并使用 await 调用。
我的一个函数将需要一个保存的状态变量 - 计算中使用的时间偏移量,偶尔需要由用户手动更新。
我不能在主线程中使用普通的全局变量——协程看不到它们。在多个协程之间保留状态变量的明智设计模式是什么?
我有一些生成器做一些搜索的东西,我使用另一个生成器包装它们:
def searching_stuff_1():
# searching
yield 1
# and searching
yield 2
yield 3
def searching_stuff_2():
yield 4
yield 5
def gen():
yield from searching_stuff_1()
yield from searching_stuff_2()
for result in gen():
print(result)
Run Code Online (Sandbox Code Playgroud)
所以现在我想知道如何将其重写为异步版本,这可以在searching_stuff_1和searching_stuff_2中产生多个值.
我在努力:
import asyncio
async def searching_stuff_1():
f = asyncio.Future()
result = []
await asyncio.sleep(1)
#searching
result.append(1)
#searching
result.append(2)
result.append(3)
f.set_result(result)
return f
async def searching_stuff_2():
f = asyncio.Future()
result = []
await asyncio.sleep(1)
result.append(4)
result.append(5)
f.set_result(result)
return f
async def producer():
coros = [searching_stuff_1(), searching_stuff_2()]
for …Run Code Online (Sandbox Code Playgroud) 我正在学习协程,我遇到了以下令人惊讶的(对我而言)行为。我想要一张平行地图。我考虑了4个解决方案:
map,没有并行性pmap从这里。coroutineScope并使用GlobalScope.parallelStream.编码:
import kotlinx.coroutines.*
import kotlin.streams.toList
import kotlin.system.measureNanoTime
inline fun printTime(msg: String, f: () -> Unit) =
println("${msg.padEnd(15)} time: ${measureNanoTime(f) / 1e9}")
suspend fun <T, U> List<T>.pmap(f: (T) -> U) = coroutineScope {
map { async { f(it) } }.map { it.await() }
}
suspend fun <T, U> List<T>.pmapGlob(f: (T) -> U) =
map { GlobalScope.async { f(it) } }.map { it.await() …Run Code Online (Sandbox Code Playgroud) parallel-processing performance coroutine kotlin kotlin-coroutines
我是 Kotlin 和 Android Studio 的新手,我目前的问题是......
我正在尝试让 Codelabs“android-room-with-a-view-kotlin”工作,同时修复各种构建错误,我认为我的 build.gradle 变得非常混乱!我通过添加依赖项更正了Word.kt 上的最后一次构建失败
kapt 'androidx.room:room-ktx:2.2.1'
Run Code Online (Sandbox Code Playgroud)
下一个构建在WordDao.kt上更进一步,但由于相同类型的错误而失败。
WordDao.java:21: error: To use Coroutine features, you must add `ktx` artifact from Room as a dependency. androidx.room:room-ktx:<version>
Run Code Online (Sandbox Code Playgroud)
我无法继续,因为我不知道要在 build.gradle 中更改什么,因为我已经添加了该依赖项?
正如我已经说过我的文件现在很迷茫,我将不胜感激任何以使其更明智的援助。谢谢, DaveInUk
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "kotlin-kapt"
android {
compileSdkVersion 28
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.prepopplus"
//was minSdkVersion 15 Note Old phone is API16
minSdkVersion 21
targetSdkVersion 28
versionCode 1 …Run Code Online (Sandbox Code Playgroud) 我刚刚创建了一个应用程序,其中我的函数 getdata() 每秒调用一次以从服务器获取新数据,而 updateui() 函数将更新 UI 中的视图我没有在我的应用程序中使用任何异步任务或协程我想这样做请告诉我我怎么能做到这一点。
这是我的代码...
private fun getdata(){
try {
val api = RetroClient.getApiService()
call = api.myJSON
call!!.enqueue(object : Callback<ProductResponse> {
override fun onResponse(
call: Call<ProductResponse>,
response: Response<ProductResponse>
) {
if (response.isSuccessful) {
productList = response.body()!!.data
for (list in productList) {
if (list.BB.equals("AAA")) {
aProductList.add(list)
}
}
if (recyclerView.adapter != null) {
eAdapter!!.updatedata(aProductList)
}
updateui()
}
}
override fun onFailure(call: Call<ProductResponse>, t: Throwable) {
println("error")
}
})
} catch (ex: Exception) {
} catch (ex: OutOfMemoryError) { …Run Code Online (Sandbox Code Playgroud) 下面是我想强调的差异的一个简单示例。
使用协程:
public float repeatRate = 5f;
void Start()
{
StartCoroutine("RepeatSomething");
}
IEnumerator RepeatSomething()
{
while (true)
{
yield return new WaitForSeconds(repeatRate);
// Do something
}
}
Run Code Online (Sandbox Code Playgroud)
使用Update()和Time.deltaTime:
public float repeatRate = 5f;
private float timer = 0;
void Update()
{
if (timer < 0)
{
// Do something
timer = repeatRate;
}
timer -= Time.deltaTime;
}
Run Code Online (Sandbox Code Playgroud)
我什么时候应该使用一个而不是另一个,每个的优点/缺点是什么?
我一直在学习 C++20 中的新功能,并试图了解共同讨论的共同例程的“生成器”用例。我试图在这里创建一个小例子,但如果有错误,我深表歉意:
generator<int> Generate() {
int i = 0;
while(1) {
co_yield i++;
}
}
int main()
{
auto gen { Generate() };
for (int x = 0; x < 10; ++x) {
gen.next();
std::cout << gen.getValue() << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是我看不出这与具有静态变量的函数有何不同,例如:
auto gen() {
static int i = 0;
return i++;
}
int main()
{
for (int x = 0; x < 10; ++x)
std::cout << gen() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想我可能会看到异步 I/O 是一个用例,尤其是使用co_await …
coroutine ×10
kotlin ×4
android ×3
python ×3
c# ×2
generator ×2
yield ×2
android-room ×1
async-await ×1
asynchronous ×1
c++ ×1
c++20 ×1
fiber ×1
ienumerator ×1
performance ×1
python-3.x ×1
time ×1