下面提到了ViewModel,Repository和Dao类。
在片段中实例化视图模型。
playlistVideoViewModel = ViewModelProviders.of(this).get(PlaylistVideoViewModel.class);
playlistVideoViewModel.getAllPlaylistVideos(String.valueOf(currentBucketId)).observe(this, new PlaylistSongObserver());
查看模型类:
public class PlaylistVideoViewModel extends AndroidViewModel {
private MutableLiveData<List<PlaylistSong>> allPlaylistSongs;
private PlaylistVideoRepo playlistVideoRepo;
public PlaylistVideoViewModel(@NonNull Application application) {
super(application);
playlistVideoRepo = new PlaylistVideoRepo(application);
allPlaylistSongs = new MutableLiveData<>();
}
public LiveData<List<PlaylistSong>> getAllPlaylistVideos(String playlistId) {
new GetPlaylistSongs().execute(playlistId);
return allPlaylistSongs;
}
public void delete(String path) {
playlistVideoRepo.delete(path);
}
@SuppressLint("StaticFieldLeak")
class GetPlaylistSongs extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
allPlaylistSongs.postValue(playlistVideoRepo.getAllPlaylistSongs(strings[0]));
return null;
}
}}
存储库:
class PlaylistVideoRepo {
private final PlaylistSongDao playlistSongDao;
PlaylistVideoRepo(Application application) {
AppDatabase appDatabase = AppDatabase.getDatabase(application);
playlistSongDao = appDatabase.playlistSongDao();
}
public List<PlaylistSong> getAllPlaylistSongs(String playlistId) {
return playlistSongDao.getAllPlaylistSongs(playlistId);
}
public void delete(String path) {
new DeletePlaylistVideoAsyncTask(playlistSongDao).execute(path);
}}
道:
@Dao
public interface PlaylistSongDao {
@Query("SELECT * FROM " + PlaylistVideoConstants.TABLE_NAME +
" WHERE " + PlaylistVideoConstants.Columns.PLAYLIST_ID + " = :playlistId")
List<PlaylistSong> getAllPlaylistSongs(String playlistId);
@Query("DELETE FROM "+ PlaylistVideoConstants.TABLE_NAME + " WHERE " + PlaylistVideoConstants.Columns.PATH + " = :path")
void delete(String path);}
现在的问题是每当我要删除任何数据时。我的观察者没有收到任何回调。
如果我做错了任何事情,请纠正。
答案 0 :(得分:1)
我假设您正在观察allPlaylistSongs
。按路径删除时,永远不会更新该MutableLiveData
。有两种方法可以解决问题。
MutableLiveData
。因此,您可以通过再次执行GetPlaylistSongs
任务来从回购中重新加载所有歌曲。MutableLiveData
。LiveData
而不只是价值。这样,数据库中的任何更改都将传播给您的观察者。示例:
@Dao
public interface PlaylistSongDao {
@Query("SELECT * FROM " + PlaylistVideoConstants.TABLE_NAME +
" WHERE " + PlaylistVideoConstants.Columns.PLAYLIST_ID + " = :playlistId")
LiveData<List<PlaylistSong>> getAllPlaylistSongs(String playlistId);
@Query("DELETE FROM "+ PlaylistVideoConstants.TABLE_NAME + " WHERE " + PlaylistVideoConstants.Columns.PATH + " = :path")
void delete(String path);}
通过将其更改为LiveData
,您现在可以删除GetPlaylistSongs
任务,并且可以直接将LiveData
对象传递到存储库,然后传递给Fragment(当然,您可能需要的任何转换)。
我希望这会有所帮助。