New feature: resumable subs that return a value

Erel

B4X founder
Staff member
Licensed User
Longtime User
As explained in the resumable subs tutorial it is not possible to directly return a value from a resumable sub. The reason for this limitation is that the code flow returns to the calling sub before the resumable sub completed.

As developers sometime do need to wait for a resumable sub to complete and return a value, a pattern based on CallSubDelayed with Wait For was suggested.
However this solution is not perfect as only a single "Wait For" can wait for the result (there is no sender filter parameter) and only subs in the current module can catch the event.

The next update of B4A, B4J and B4i will provide a better solution:
B4X:
Sub DownloadImage (url As String) As ResumableSub
   Dim j As HttpJob
   j.Initialize("", Me)
   j.Download(url)
   Wait For (j) JobDone(j As HttpJob)
   Dim bmp As Bitmap
   If j.Success Then
     bmp = j.GetBitmap
   Else
     bmp = ErrorBitmap
   End If
   j.Release
   Return bmp
End Sub

Resumable subs can return the new ResumableSub type.
Such subs can return values with the Return keyword.

The returned object can be used as the sender filter parameter for Wait For that waits for the Complete event:
B4X:
Wait For (DownloadImage(ImageLink)) Complete (bmp As Bitmap)
ImageView1.Bitmap = bmp

The resumable sub can be safely called multiple times. It can also be put in a class module:
B4X:
Wait For (ClassInstance.DownloadImage(ImageLink)) Complete (bmp As Bitmap)
 
Top