refactor(LocalDataSource, PostRepository, ChatScreen): enhance database handling and message loading
- Introduced a promise-based initialization mechanism in LocalDataSource to prevent concurrent initialization issues. - Updated PostRepository to utilize an enqueueWrite method for database operations, ensuring thread-safe writes. - Refactored ChatScreen to improve message loading logic, including preloading history and managing scroll behavior more effectively. - Enhanced message rendering logic to maintain correct indices in inverted lists and optimize user experience during scrolling.
This commit is contained in:
@@ -231,10 +231,19 @@ const isRecoverableDbError = (error: unknown): boolean => {
|
||||
const message = String(error);
|
||||
return (
|
||||
message.includes('NativeDatabase.prepareAsync') ||
|
||||
message.includes('NullPointerException')
|
||||
message.includes('NullPointerException') ||
|
||||
message.includes('Cannot use shared object that was already released') ||
|
||||
message.includes('NativeStatement')
|
||||
);
|
||||
};
|
||||
|
||||
const recoverDbConnection = async (): Promise<SQLite.SQLiteDatabase> => {
|
||||
// 清理当前引用,随后用当前用户上下文重建连接
|
||||
db = null;
|
||||
await initDatabase(currentDbUserId || undefined);
|
||||
return getDb();
|
||||
};
|
||||
|
||||
const withDbRead = async <T>(operation: (database: SQLite.SQLiteDatabase) => Promise<T>): Promise<T> => {
|
||||
let database = await getDb();
|
||||
try {
|
||||
@@ -244,8 +253,7 @@ const withDbRead = async <T>(operation: (database: SQLite.SQLiteDatabase) => Pro
|
||||
throw error;
|
||||
}
|
||||
console.error('数据库读取异常,尝试重连后重试:', error);
|
||||
db = null;
|
||||
database = await getDb();
|
||||
database = await recoverDbConnection();
|
||||
return operation(database);
|
||||
}
|
||||
};
|
||||
@@ -259,7 +267,7 @@ const enqueueWrite = async <T>(operation: () => Promise<T>): Promise<T> => {
|
||||
throw error;
|
||||
}
|
||||
console.error('数据库写入异常,尝试重连后重试:', error);
|
||||
db = null;
|
||||
await recoverDbConnection();
|
||||
return operation();
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user