|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package com.azure.resourcemanager.network.implementation; |
| 5 | + |
| 6 | +import com.azure.core.http.rest.PagedFlux; |
| 7 | +import com.azure.core.http.rest.PagedResponse; |
| 8 | +import com.azure.core.http.rest.PagedResponseBase; |
| 9 | +import com.azure.core.util.paging.PageRetriever; |
| 10 | +import reactor.core.publisher.Flux; |
| 11 | + |
| 12 | +import java.util.function.Function; |
| 13 | +import java.util.function.Supplier; |
| 14 | +import java.util.stream.Collectors; |
| 15 | + |
| 16 | +/** |
| 17 | + * Utility class for conversion of PagedResponse. |
| 18 | + */ |
| 19 | +final class PagedConverterForMergedPagedFlux { |
| 20 | + |
| 21 | + private PagedConverterForMergedPagedFlux() { |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Applies map transform to elements of PagedFlux. |
| 26 | + * <p> |
| 27 | + * Use this mapPage (not the one in PagedConverter) when the PagedFlux is produced by PagedConverter.mergePagedFlux. |
| 28 | + * |
| 29 | + * @param pagedFlux the input of PagedFlux. |
| 30 | + * @param mapper the map transform of element T to element S. |
| 31 | + * @param <T> input type of PagedFlux. |
| 32 | + * @param <S> return type of PagedFlux. |
| 33 | + * @return the PagedFlux with elements in PagedResponse transformed. |
| 34 | + */ |
| 35 | + static <T, S> PagedFlux<S> mapPage(PagedFlux<T> pagedFlux, Function<T, S> mapper) { |
| 36 | + Supplier<PageRetriever<String, PagedResponse<S>>> provider = () -> (continuationToken, pageSize) -> { |
| 37 | + // take all the pages, do not use .take(1) |
| 38 | + Flux<PagedResponse<T>> flux |
| 39 | + = (continuationToken == null) ? pagedFlux.byPage() : pagedFlux.byPage(continuationToken); |
| 40 | + return flux.map(mapPagedResponse(mapper)); |
| 41 | + }; |
| 42 | + return PagedFlux.create(provider); |
| 43 | + } |
| 44 | + |
| 45 | + private static <T, S> Function<PagedResponse<T>, PagedResponse<S>> mapPagedResponse(Function<T, S> mapper) { |
| 46 | + return pagedResponse -> new PagedResponseBase<Void, S>(pagedResponse.getRequest(), |
| 47 | + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), |
| 48 | + pagedResponse.getValue().stream().map(mapper).collect(Collectors.toList()), |
| 49 | + pagedResponse.getContinuationToken(), null); |
| 50 | + } |
| 51 | +} |
0 commit comments