B4J Question How to get Return value of .Completed ResumableSub ?

emexes

Expert
Licensed User
eg start 4 tasks, of unknown execution time:

B4X:
Dim rs(4) as ResumableSub

rs(0) = GiveItAGo(1000)
rs(1) = GiveItAGo(1001)
rs(2) = GiveItAGo(1002)
rs(3) = GiveItAGo(1003)

and then later, see which ones had any luck:

B4X:
For I = 0 to 4 - 1
    If rs(I).Completed Then
        Log( how to get return value of rs(I) )
    End If
Next
 

emexes

Expert
Licensed User
You must use Wait For to wait for the results.

Is there a way to wait for multiple ResumableSubs at the same time?

My problem is that I don't know which ResumableSub is going to finish first, so I don't know what order to wait for them in.

I did think of using global variables, but I figured that the .Completed method was there for a reason, and the only reason I could think of was to let you know that the result was ready.

As I understand it: if a ResumableSub completes and returns a value, and there's nothing waiting to catch the message, then the result is lost - is this correct?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Yes, but it works a bit differently.

Two examples:
B4X:
Dim result As List
result.Initialize    
For i = 1 To 10
    SlowSub(i, result, 10)
Next
Wait For ResultsAvailable
Log(result)


Private Sub SlowSub (input As Int, result As List, ExpectedNumberOfResults As Int)
    Sleep(Rnd(1, 1000))
    result.Add(input * input)
    If result.Size = ExpectedNumberOfResults Then
        CallSubDelayed(Me, "ResultsAvailable")
    End If
End Sub

I like this one better:
B4X:
Dim result As List
result.Initialize
For i = 1 To 10
    SlowSub(i, result)
Next
Do While result.Size < 10
    Sleep(50)
Loop
Log(result)

Private Sub SlowSub (input As Int, result As List)
    Sleep(Rnd(1, 1000))
    result.Add(input * input)
End Sub
The second one looks like a busy loop but it isn't. Its performance will be fine and it is actually more robust and safer (you will not get problems if you call SlowSub from some other place at the same time).
 
Upvote 0
Top