简体   繁体   English

使用RxJava从异步调用返回值?

[英]Using RxJava to return value from asynchronous call?

Okay, so what I'm trying to do is collect a list of user_uid's from firebase then for each user_uid fetch an image url and combine it and return one Object. 好的,所以我想做的是从firebase收集一个user_uid的列表,然后为每个user_uid获取一个图像URL并将其组合并返回一个Object。 The problem I'm running into is returning the Object from the asynchronous call. 我遇到的问题是从异步调用返回对象。 I'm trying to implement rxjava to achieve this, but I'm still getting empty Objects. 我正在尝试实现rxjava来实现这一点,但是我仍在获取空对象。 below I'll have code and database structure so you can see what I'm trying to achieve, thank you all in advanced for any help 下面,我将提供代码和数据库结构,以便您可以了解我要实现的目标,在此先感谢所有帮助

this is the database structure: 这是数据库结构: 在此处输入图片说明

Asynchronous call: 异步调用:

private Note createNoteWithArtists(Note note, ArrayList<String> user_uids) {
    DatabaseReference db_users = db_root.child("Users");
    ArrayList<User> artists = new ArrayList<>();
    Note note = note;
    for (String each_uid : user_uids) {
        db_users.child(each_uid).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String uid = dataSnapshot.getKey();
                String image = dataSnapshot.child("image").getValue(String.class);
                String username = dataSnapshot.child("username").getValue(String.class);
                User user = new User(username, null, image, uid);
                artists.add(user);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    }
    note.setArtists(artists);
    return Note;
}

attempting to use RxJava: 尝试使用RxJava:

io.reactivex.Observable<Note> observable = io.reactivex.Observable.create(subscriber -> {
                subscriber.onNext(createNoteWithArtists(note, artists));
                subscriber.onComplete();
            });
            observable.subscribe(note -> loadNoteResults.NoteLoaded(note, true)).dispose();

It returns the note, but the nested artists object is still empty :/ 它返回注释,但是嵌套的artist对象仍然为空:/

Observable.create(...) will emit a Note as soon as createNotWitArtists returns a value. 一旦createNotWitArtists返回一个值, Observable.create(...)将发出一个Note Your RxJava attempt is functionally equivalent to: 您的RxJava尝试在功能上等效于:

Note emptyNote = createNoteWithArtists(note, artists);
loadNoteResults.NoteLoaded(emptyNote , true);

Take a look at this approach: 看一下这种方法:

private Single<User> getUser(String user_uid) {
    DatabaseReference db_users = db_root.child("Users");
    return Single.create(emitter -> {
        db_users.child(each_uid).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String uid = dataSnapshot.getKey();
                String image = dataSnapshot.child("image").getValue(String.class);
                String username = dataSnapshot.child("username").getValue(String.class);
                User user = new User(username, null, image, uid);
                emitter.onSuccess(user);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                emitter.onError(databaseError);
            }
        });
    });
}

The idea is to use Single.create that emits when each onDataChange is called. 这个想法是使用Single.create ,它在每次onDataChange时发出。

Then you can combine all Single s using toList() like this: 然后可以使用toList()组合所有Single如下所示:

// Note note
// List<String> artist

Observable.fromIterable(artistIds) // Observable<String>
    .flatMapSingle(this::getUser) // Observable<User>
    .toList() // Single<List<User>>
    .subscribe( artists -> {
        note.setArtists(artists);
        loadNoteResults.NoteLoaded(note, true);
    });

Also, don't forget to put schedulers whenever it is needed. 另外,不要忘记在需要时放置调度程序。

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

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