Skip to content
Open
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
38 changes: 36 additions & 2 deletions Assets/pocketbase-unity/Runtime/Sse/DownloadHandlerSseBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

using System.Text;
using System.Threading;
using UnityEngine.Networking;

namespace PocketBaseSdk
Expand All @@ -12,6 +13,13 @@ public abstract class DownloadHandlerSseBase : DownloadHandlerScript
{
private readonly StringBuilder _currentLine = new();
private readonly Decoder _utf8Decoder = Encoding.UTF8.GetDecoder();
private static readonly SynchronizationContext UnitySyncContext;

static DownloadHandlerSseBase()
{
// Capture Unity's main thread SynchronizationContext on class initialization
UnitySyncContext = SynchronizationContext.Current;
}

protected DownloadHandlerSseBase(byte[] buffer) : base(buffer)
{
Expand All @@ -34,11 +42,24 @@ protected override bool ReceiveData(byte[] newData, int dataLength)

if (c == '\n')
{
OnNewLineReceived(_currentLine.ToString());
string line = _currentLine.ToString();
_currentLine.Clear();

// Marshal to Unity main thread before processing
if (UnitySyncContext != null)
{
string lineToProcess = line; // Capture for closure
UnitySyncContext.Post(_ => OnNewLineReceived(lineToProcess), null);
}
else
{
OnNewLineReceived(line);
}
}
else
{
_currentLine.Append(c);
}
}

return true;
Expand All @@ -47,7 +68,20 @@ protected override bool ReceiveData(byte[] newData, int dataLength)
protected override void CompleteContent()
{
if (_currentLine.Length > 0)
OnNewLineReceived(_currentLine.ToString());
{
string line = _currentLine.ToString();

// Marshal to Unity main thread before processing
if (UnitySyncContext != null)
{
string lineToProcess = line; // Capture for closure
UnitySyncContext.Post(_ => OnNewLineReceived(lineToProcess), null);
}
else
{
OnNewLineReceived(line);
}
}
}
}
}