gpt4 book ai didi

Android:从 Rx Android Retrofit 返回

转载 作者:行者123 更新时间:2023-11-29 00:03:39 24 4
gpt4 key购买 nike

我有一个返回 Observable 的类方法。 observable 包含传递给 post 方法所需的授权 key 。我能够从一个类返回值,但无法按时在另一个类中捕获它。我正在阅读,人们使用 Observable.blocking.first 阻塞当前线程,这不是一个好方法。任何人都知道如何在另一个类(class)捕获它。这是我的代码:

返回可观察类:

public class GetAuthenticationToken {
String authentication_token;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://abc.def.com/")
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
GetTokenInterface service = retrofit.create(GetTokenInterface.class);

Observable<String> response_call = service.getToken1(setAPI_KEY, getaccesstoken);
String savedToken;
@CheckResult
public Observable<String> getToken() {
return service.getToken1(setAPI_KEY, getaccesstoken)
.subscribeOn(Schedulers.newThread())
.doOnNext(new Action1<String>() {
public void call(String token) {
savedToken = token;
}
})
.observeOn(AndroidSchedulers.mainThread());
}

public String getSavedToken() {
return savedToken;
}
}

但不知道在不阻塞线程的情况下在另一个类中准时捕获它:

  public class Post_To_Api {
GetAuthenticationToken getauthenticationtoken = new GetAuthenticationToken();
Observable<String> generated_token = getauthenticationtoken.getToken(); //Dont know to get it here on time without blocking thread
generated_token.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {

System.out.print("Complete");
}

@Override
public void onError(Throwable e) {

System.out.print("Fail");
}

@Override
public void onNext(String token) {
authentication_token = token; //getting correct value here
}
});

}

最佳答案

解决方案是让事情保持异步而不是阻塞。

MyApiServide myApiService = // Create your retrofit API service 

public Observable<SomeApiResult> requestApiItem() {
return getApiToken()
.flatMap(new Func1<String, Observable<SomeApiResult>>() {
public Observable<SomeApiResult> call(String token) {
return myApiService.requestItem(token);
}
})
.subscribeOn(Schedulers.io())
}


public Observable<String> getApiToken() {
// get token from API as you have
}

// Were you use the API
requestApiItem()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<SomeApiResult>() {
@Override
public void onCompleted() {
System.out.print("Complete");
}

@Override
public void onError(Throwable e) {
System.out.print("Fail");
}

@Override
public void onNext(SomeApiResult apiResult) {
myView.setText(apiResult.someValue); // or whatever you want to do with result.
}
});

关于Android:从 Rx Android Retrofit 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43685428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com