Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution to make network call on main thread #190

Merged
merged 2 commits into from
Dec 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}
}
}
}
}