Skip to content

Commit a3bb763

Browse files
authored
Merge pull request #190 from maifeeulasad/stuck-fix
solution to make network call on main thread
2 parents 89ede11 + f3228a6 commit a3bb763

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ RestClient.GetArray<Post>(api + "/posts").Then(response => {
5555
- Handle HTTP exceptions in a better way
5656
- Retry HTTP requests easily
5757
- Open Source 🦄
58+
- Utility to work during scene transition
5859

5960
## Supported platforms 📱 🖥
6061
The [UnityWebRequest](https://docs.unity3d.com/Manual/UnityWebRequest.html) system supports most Unity platforms:
@@ -112,6 +113,13 @@ RestClient.Head("https://jsonplaceholder.typicode.com/posts").Then(response => {
112113
});
113114
```
114115

116+
## Handling during scene transition
117+
```csharp
118+
ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
119+
//Any API call using RestClient
120+
});
121+
```
122+
115123
### Generic Request Method
116124
And we have a generic method to create any type of request:
117125
```csharp
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Collections.Concurrent;
4+
using UnityEngine;
5+
6+
namespace Proyecto26.Helper {
7+
8+
/// <summary>
9+
/// Original solution from: https://stackoverflow.com/a/53818416/10305444
10+
/// Should also read: https://gamedev.stackexchange.com/a/195298/126092
11+
/// Usage:
12+
/// ```
13+
/// ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
14+
/// Code here will be called in the main thread...
15+
/// });
16+
/// ```
17+
/// </summary>
18+
public class ExecuteOnMainThread: MonoBehaviour {
19+
20+
/// <summary>
21+
/// Store all instance of Action's and try to invoke them
22+
/// </summary>
23+
public static readonly ConcurrentQueue < Action > RunOnMainThread = new ConcurrentQueue < Action > ();
24+
25+
/// <summary>
26+
/// Unity's Update method
27+
/// </summary>
28+
void Update() {
29+
if (!RunOnMainThread.IsEmpty) {
30+
while (RunOnMainThread.TryDequeue(out var action)) {
31+
action?.Invoke();
32+
}
33+
}
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)