Skip to content

Commit 3c223b4

Browse files
committed
Moved both pages to use a watch query.
1 parent f091b52 commit 3c223b4

File tree

6 files changed

+80
-47
lines changed

6 files changed

+80
-47
lines changed

demos/TodoSQLite/Data/PowerSyncData.cs

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,33 @@ namespace TodoSQLite.Data;
88

99
public class PowerSyncData
1010
{
11-
private PowerSyncDatabase _db;
11+
public PowerSyncDatabase _db;
1212
private ILogger _logger;
13+
private bool _isConnected;
14+
15+
16+
public PowerSyncData()
17+
{
18+
Console.WriteLine("Creating PowerSyncData instance");
19+
}
1320

1421
public string UserId { get; set; } = "";
22+
public bool IsConnected
23+
{
24+
get => _isConnected;
25+
private set
26+
{
27+
if (_isConnected != value)
28+
{
29+
_isConnected = value;
30+
ConnectionStatusChanged?.Invoke(this, EventArgs.Empty);
31+
}
32+
}
33+
}
1534

16-
17-
async Task Init()
35+
public event EventHandler ConnectionStatusChanged;
36+
37+
public async Task Init()
1838
{
1939
if (_db != null) return;
2040

@@ -25,7 +45,7 @@ async Task Init()
2545
});
2646
_logger = loggerFactory.CreateLogger("PowerSyncLogger");
2747

28-
var dbPath = Path.Combine(FileSystem.AppDataDirectory, "mydb.db");
48+
var dbPath = Path.Combine(FileSystem.AppDataDirectory, "examplsee.db");
2949
var factory = new MAUISQLiteDBOpenFactory(new MDSQLiteOpenFactoryOptions()
3050
{
3151
DbFilename = dbPath
@@ -40,15 +60,8 @@ async Task Init()
4060

4161
var nodeConnector = new NodeConnector();
4262
UserId = nodeConnector.UserId;
43-
await _db.Connect(nodeConnector);
44-
}
45-
46-
// List operations
47-
public async Task<List<TodoList>> GetListsAsync()
48-
{
49-
await Init();
50-
var results = await _db.GetAll<TodoList>("SELECT * FROM lists ORDER BY created_at DESC");
51-
return results.ToList();
63+
64+
_db.Connect(nodeConnector);
5265
}
5366

5467
public async Task SaveListAsync(TodoList list)
@@ -63,7 +76,7 @@ await _db.Execute(
6376
else
6477
{
6578
await _db.Execute(
66-
"INSERT INTO lists (id, name, owner_id, created_at) VALUES (uuid(), ?, ?, ?)",
79+
"INSERT INTO lists (id, created_at, name, owner_id, created_at) VALUES (uuid(), datetime(), ?, ?, ?)",
6780
[list.Name, UserId, DateTime.UtcNow.ToString("o")]);
6881
}
6982
}
@@ -76,15 +89,6 @@ public async Task DeleteListAsync(TodoList list)
7689
await _db.Execute("DELETE FROM todos WHERE list_id = ?", [listId]);
7790
await _db.Execute("DELETE FROM lists WHERE id = ?", [listId]);
7891
}
79-
public async Task<List<TodoItem>> GetItemsAsync(string listId)
80-
{
81-
await Init();
82-
var results = await _db.GetAll<TodoItem>(
83-
"SELECT * FROM todos WHERE list_id = ? ORDER BY created_at DESC", [listId]);
84-
85-
return results.ToList();
86-
}
87-
8892
public async Task SaveItemAsync(TodoItem item)
8993
{
9094
await Init();
@@ -106,8 +110,8 @@ await _db.Execute(
106110
{
107111
await _db.Execute(
108112
@"INSERT INTO todos
109-
(id, list_id, description, created_at, completed, created_by)
110-
VALUES (uuid(), ?, ?, ?, ?, ?)",
113+
(id, list_id, description, created_at, completed, created_by, created_at)
114+
VALUES (uuid(), ?, ?, ?, ?, ?, datetime())",
111115
[
112116
item.ListId,
113117
item.Description,

demos/TodoSQLite/Resources/Images/add.svg

Lines changed: 0 additions & 1 deletion
This file was deleted.

demos/TodoSQLite/TodoSQLite.csproj

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,6 @@
4141
<!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
4242
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
4343
</ItemGroup>
44-
45-
<ItemGroup>
46-
<None Remove="Resources\Images\add.svg" />
47-
</ItemGroup>
4844

4945
<ItemGroup>
5046
<PackageReference Include="sqlite-net-pcl" Version="1.8.116" />

demos/TodoSQLite/Views/ListsPage.xaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
x:Class="TodoSQLite.Views.ListsPage"
55
Title="Todo Lists">
66
<ContentPage.ToolbarItems>
7-
<ToolbarItem IconImageSource="wifi.png"
7+
<ToolbarItem x:Name="WifiStatusItem"
88
Order="Primary"
99
Priority="0"/>
1010
</ContentPage.ToolbarItems>
Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using PowerSync.Common.Client;
12
using TodoSQLite.Models;
23
using TodoSQLite.Data;
34

@@ -6,17 +7,36 @@ namespace TodoSQLite.Views;
67
public partial class ListsPage : ContentPage
78
{
89
private readonly PowerSyncData _database;
10+
private bool connected = false;
911

1012
public ListsPage(PowerSyncData database)
1113
{
1214
InitializeComponent();
1315
_database = database;
16+
UpdateWifiStatus();
17+
}
18+
19+
private void UpdateWifiStatus()
20+
{
21+
WifiStatusItem.IconImageSource = connected ? "wifi.png" : "wifi_off.png";
1422
}
1523

1624
protected override async void OnAppearing()
1725
{
1826
base.OnAppearing();
19-
ListsCollection.ItemsSource = await _database.GetListsAsync();
27+
await _database.Init();
28+
29+
await _database._db.Watch("select * from lists", null, new WatchHandler<TodoList>
30+
{
31+
OnResult = (results) =>
32+
{
33+
MainThread.BeginInvokeOnMainThread(() => { ListsCollection.ItemsSource = results.ToList(); });
34+
},
35+
OnError = (error) =>
36+
{
37+
Console.WriteLine("Error: " + error.Message);
38+
}
39+
});
2040
}
2141

2242
private async void OnAddClicked(object sender, EventArgs e)
@@ -26,23 +46,21 @@ private async void OnAddClicked(object sender, EventArgs e)
2646
{
2747
var list = new TodoList { Name = name };
2848
await _database.SaveListAsync(list);
29-
ListsCollection.ItemsSource = await _database.GetListsAsync();
3049
}
3150
}
3251

3352
private async void OnDeleteClicked(object sender, EventArgs e)
3453
{
3554
var button = (Button)sender;
3655
var list = (TodoList)button.CommandParameter;
37-
38-
bool confirm = await DisplayAlert("Confirm Delete",
39-
$"Are you sure you want to delete the list '{list.Name}'?",
56+
57+
bool confirm = await DisplayAlert("Confirm Delete",
58+
$"Are you sure you want to delete the list '{list.Name}'?",
4059
"Yes", "No");
41-
60+
4261
if (confirm)
4362
{
4463
await _database.DeleteListAsync(list);
45-
ListsCollection.ItemsSource = await _database.GetListsAsync();
4664
}
4765
}
4866

@@ -54,4 +72,4 @@ private async void OnListSelected(object sender, SelectionChangedEventArgs e)
5472
ListsCollection.SelectedItem = null;
5573
}
5674
}
57-
}
75+
}

demos/TodoSQLite/Views/TodoListPage.xaml.cs

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
using System.Collections.ObjectModel;
2+
using PowerSync.Common.Client;
23
using TodoSQLite.Data;
34
using TodoSQLite.Models;
45

56
namespace TodoSQLite.Views;
67

78
public partial class TodoListPage : ContentPage
89
{
9-
private readonly PowerSyncData _database;
10+
public readonly PowerSyncData _database;
1011
private readonly TodoList _list;
1112

1213
public TodoListPage(PowerSyncData database, TodoList list)
@@ -20,7 +21,17 @@ public TodoListPage(PowerSyncData database, TodoList list)
2021
protected override async void OnAppearing()
2122
{
2223
base.OnAppearing();
23-
TodoItemsCollection.ItemsSource = await _database.GetItemsAsync(_list.ID);
24+
await _database._db.Watch("select * from todos", null, new WatchHandler<TodoItem>
25+
{
26+
OnResult = (results) =>
27+
{
28+
MainThread.BeginInvokeOnMainThread(() => { TodoItemsCollection.ItemsSource = results.ToList(); });
29+
},
30+
OnError = (error) =>
31+
{
32+
Console.WriteLine("Error: " + error.Message);
33+
}
34+
});
2435
}
2536

2637
private async void OnAddClicked(object sender, EventArgs e)
@@ -34,7 +45,6 @@ private async void OnAddClicked(object sender, EventArgs e)
3445
ListId = _list.ID
3546
};
3647
await _database.SaveItemAsync(todo);
37-
TodoItemsCollection.ItemsSource = await _database.GetItemsAsync(_list.ID);
3848
}
3949
}
4050

@@ -50,7 +60,6 @@ private async void OnDeleteClicked(object sender, EventArgs e)
5060
if (confirm)
5161
{
5262
await _database.DeleteItemAsync(todo);
53-
TodoItemsCollection.ItemsSource = await _database.GetItemsAsync(_list.ID);
5463
}
5564
}
5665

@@ -59,9 +68,17 @@ private async void OnCheckBoxChanged(object sender, CheckedChangedEventArgs e)
5968
if (sender is CheckBox checkBox &&
6069
checkBox.Parent?.Parent?.BindingContext is TodoItem todo)
6170
{
62-
todo.Completed = e.Value;
63-
todo.CompletedAt = e.Value ? DateTime.UtcNow.ToString("o") : null;
64-
await _database.SaveItemAsync(todo);
71+
if (e.Value == true && todo.CompletedAt == null)
72+
{
73+
todo.Completed = e.Value;
74+
todo.CompletedAt = DateTime.UtcNow.ToString("o");
75+
await _database.SaveItemAsync(todo);
76+
} else if (e.Value == false && todo.CompletedAt != null)
77+
{
78+
todo.Completed = e.Value;
79+
todo.CompletedAt = null; // Uncheck, clear completed time
80+
await _database.SaveItemAsync(todo);
81+
}
6582
}
6683
}
6784

@@ -77,7 +94,6 @@ private async void OnItemSelected(object sender, SelectionChangedEventArgs e)
7794
{
7895
selectedItem.Description = newDescription;
7996
await _database.SaveItemAsync(selectedItem);
80-
TodoItemsCollection.ItemsSource = await _database.GetItemsAsync(_list.ID);
8197
}
8298

8399
TodoItemsCollection.SelectedItem = null;

0 commit comments

Comments
 (0)