B4J Question [PyBridge] Calling asynchronous functions in python

Mariano Ismael Castro

Active Member
Licensed User
Hi I'm trying to call an asynchronous function in python using the new pybridge framework but I can't get it to work.
I attach part of my code and an example project, greetings

Python code:
Private Sub AsyncFunction As PyWrapper
    Dim Code As String = $"
import asyncio

async def AsyncFunction():
    print("Hello!")
    await asyncio.sleep(1)  #Wait 1 second asynchronously
    print("I hope you're having a nice day!")
"$
    Return Py.RunCode("AsyncFunction", Array(), Code)
End Sub

Private Sub btnAsyncFunction_Click
    Dim test As PyWrapper = AsyncFunction
    test.Print
    Wait For (test.Fetch) Complete (Result As PyWrapper)
    Result.Print
    Wait For (Py.Flush) Complete (Success As Boolean)
End Sub


P.S. Congratulations to Erel for the great framework he's made
 

Attachments

  • TestAsyncFunction.zip
    3.5 KB · Views: 24

Erel

B4X founder
Staff member
Licensed User
Longtime User
Good question!

B4X:
Private Sub AsyncFunction As ResumableSub
    Dim Code As String = $"
import asyncio

async def AsyncFunction():
    print("Hello!")
    await asyncio.sleep(1)  #Wait 1 second asynchronously
    print("I hope you're having a nice day!")
    return 10
"$
    Wait For (Py.RunCodeAwait("AsyncFunction", Array(), Code)) Complete (Result As PyWrapper)
    Return Result
End Sub

Usage:
B4X:
Wait For (AsyncFunction) Complete (Result As PyWrapper)
Log(Result.Value)

But... you will need to wait for the next update of PyBridge.
 
Upvote 0
Top