简体   繁体   English

Android Realm中的一对多关系。 处理线程

[英]One to many relationship in Android Realm. Dealing with threads

I have a one to many relationship relationship by having one song be assigned to a band, and a band has many songs. 通过将一首歌曲分配给一个乐队,我具有一对多的关系,并且一个乐队有很多歌曲。 So in the end I am assigning song.setBand( band ). 所以最后我要分配song.setBand(band)。 This all makes sense since the band is picked from a listView. 因为带是从listView中选取的,所以这一切都是有意义的。 The problem was when working with executeTransationAsync by trying to add the new song with the band. 问题是尝试通过在乐队中添加新歌曲来使用executeTransationAsync时。 It worked if there was no band picked, but otherwise I was running with thread issues. 如果没有选择频段,它可以工作,但是否则我遇到了线程问题。 I had to pick the band again while working withing the current thread. 在使用当前线程时,我不得不再次选择乐队。 Is there a better solution to do this? 有更好的解决方案吗?

public void add( Song song ){

    int bandId = song.getBand().getId();

    realm.executeTransactionAsync(thisRealm->{

                Number nextID = thisRealm.where(Song.class).max("id");

                if( nextID != null ){
                    song.setId( nextID.intValue() + 1 );
                }else{
                    song.setId( 0 );
                }

                Band band = thisRealm.where(Band.class).equalTo( "id", bandId ).findFirst();

                if( band != null ){
                    song.setBand( band );
                }else{
                    song.setBand( null );
                }

                thisRealm.copyToRealm( song );
            },
            ()->{
                publishSubject.onNext( song );
            },
            error->{
                publishSubject.onError( error );
            });
}

As far as today Aug 29, 2016 this is the right way to save an object having a one to many relationship using an asynchronous transaction. 截至2016年8月29日,这是使用异步事务保存具有一对多关系的对象的正确方法。 Thanks for your help for those who left comments. 感谢您对那些发表评论的人的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM