Replace ReactiveUI

This commit is contained in:
Jöran Malek 2024-05-02 21:44:13 +02:00
parent 43b4d50e43
commit 5584ab4ec8
41 changed files with 472 additions and 1013 deletions

View file

@ -1,7 +1,4 @@
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using DynamicData;
using Avalonia.Collections;
using InkForge.Data;
@ -9,51 +6,46 @@ using Microsoft.EntityFrameworkCore;
namespace InkForge.Desktop.Models;
public class NoteStore
public class NoteStore(IDbContextFactory<NoteDbContext> dbContextFactory)
{
private readonly IDbContextFactory<NoteDbContext> _dbContextFactory;
private readonly SourceCache<Note, int> _notesCache = new(m => m.Id);
public AvaloniaDictionary<int, Note> Notes { get; } = [];
public ReadOnlyObservableCollection<Note> Notes { get; }
public NoteStore(IDbContextFactory<NoteDbContext> dbContextFactory)
public async ValueTask Load()
{
_dbContextFactory = dbContextFactory;
await using var dbContext = await dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
Notes.Clear();
await foreach (var note in dbContext.Notes.AsAsyncEnumerable().ConfigureAwait(false))
{
Notes.Add(note.Id, Map(note));
}
}
public void AddNote(Note note)
{
using var dbContext = _dbContextFactory.CreateDbContext();
var entity = ToEntity(note);
using var dbContext = dbContextFactory.CreateDbContext();
var entity = Map(note);
var entry = dbContext.Notes.Add(entity);
dbContext.SaveChanges();
}
public Note CreateNote() => new(this);
public Note? GetById(int id)
{
if (((Note?)_notesCache.Lookup(id)) is not Note note)
if (!Notes.TryGetValue(id, out var note))
{
using var dbContext = _dbContextFactory.CreateDbContext();
using var dbContext = dbContextFactory.CreateDbContext();
if (dbContext.Notes.Find(id) is not { } dbNote)
{
return null;
}
note = ToNote(dbNote);
Notes.Add(id, note = Map(dbNote));
}
return note;
}
public IObservable<Note?> Watch(int id)
{
return _notesCache.WatchValue(id);
}
private NoteEntity ToEntity(Note note)
private NoteEntity Map(Note note)
{
return new()
{
@ -64,25 +56,26 @@ public class NoteStore
Created = note.CreatedTime,
Updated = note.UpdatedTime,
},
Parent = note.Parent switch
Parent = note.ParentId switch
{
{ Id: { } parentId } => new()
{ } parentId => new()
{
Id = parentId
},
_ => null,
}
_ => null
},
};
}
private Note ToNote(NoteEntity entity)
private Note Map(NoteEntity entity)
{
var note = CreateNote();
note.Id = entity.Id;
note.Name = entity.Value.Name;
note.CreatedTime = entity.Value.Created;
note.UpdatedTime = entity.Value.Updated;
note.ParentId = entity.Parent?.Id;
return note;
return new()
{
Id = entity.Id,
Name = entity.Value.Name,
CreatedTime = entity.Value.Created,
UpdatedTime = entity.Value.Updated,
ParentId = entity.Parent?.Id
};
}
}