Skip to content

Commit

Permalink
Merge pull request #190 from maifeeulasad/stuck-fix
Browse files Browse the repository at this point in the history
solution to make network call on main thread
  • Loading branch information
jdnichollsc committed Dec 9, 2021
2 parents 89ede11 + f3228a6 commit a3bb763
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ RestClient.GetArray<Post>(api + "/posts").Then(response => {
- Handle HTTP exceptions in a better way
- Retry HTTP requests easily
- Open Source 馃
- Utility to work during scene transition

## Supported platforms 馃摫 馃枼
The [UnityWebRequest](https://docs.unity3d.com/Manual/UnityWebRequest.html) system supports most Unity platforms:
Expand Down Expand Up @@ -112,6 +113,13 @@ RestClient.Head("https://jsonplaceholder.typicode.com/posts").Then(response => {
});
```

## Handling during scene transition
```csharp
ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
//Any API call using RestClient
});
```

### Generic Request Method
And we have a generic method to create any type of request:
```csharp
Expand Down
36 changes: 36 additions & 0 deletions src/Proyecto26.RestClient/Helpers/ExecuteOnMainThread.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using UnityEngine;

namespace Proyecto26.Helper {

/// <summary>
/// Original solution from: https://stackoverflow.com/a/53818416/10305444
/// Should also read: https://gamedev.stackexchange.com/a/195298/126092
/// Usage:
/// ```
/// ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
/// Code here will be called in the main thread...
/// });
/// ```
/// </summary>
public class ExecuteOnMainThread: MonoBehaviour {

/// <summary>
/// Store all instance of Action's and try to invoke them
/// </summary>
public static readonly ConcurrentQueue < Action > RunOnMainThread = new ConcurrentQueue < Action > ();

/// <summary>
/// Unity's Update method
/// </summary>
void Update() {
if (!RunOnMainThread.IsEmpty) {
while (RunOnMainThread.TryDequeue(out var action)) {
action?.Invoke();
}
}
}
}
}

0 comments on commit a3bb763

Please sign in to comment.